PracticeNeetCode ↗LeetCode ↗
Place n queens on an n×n chessboard so no two queens attack each other (no shared row, column, or diagonal). Return every distinct board arrangement, each as a list of strings using "Q" for a queen and "." for an empty square.
row - col and row + col, which are constant for every cell on the same diagonal.backtrack(row): if row == n, record a copy of the board's string rows.col from 0 to n: skip if col, or the diagonal keys row - col / row + col, are already in use."Q" at board[row][col], recurse with backtrack(row + 1), then undo the marks and reset the cell to ".".backtrack(0) on an all-"." board and return the recorded results.Time: O(n!) — Space: O(n²) for the board, plus O(n) recursion depth
def solveNQueens(n: int) -> list[list[str]]:
result = []
board = [["."] * n for _ in range(n)]
cols, diag1, diag2 = set(), set(), set()
def backtrack(row: int) -> None:
if row == n:
result.append(["".join(r) for r in board])
return
for col in range(n):
if col in cols or (row - col) in diag1 or (row + col) in diag2:
continue
cols.add(col)
diag1.add(row - col)
diag2.add(row + col)
board[row][col] = "Q"
backtrack(row + 1)
cols.remove(col)
diag1.remove(row - col)
diag2.remove(row + col)
board[row][col] = "."
backtrack(0)
return resultHow the solution above works, piece by piece.
row - col; every square on the same ↙ diagonal has the same row + col. Three sets turn "is this square attacked?" into O(1) lookups.row == n, all queens are placed: save the board as strings. Roughly O(n!) time.The result for n = 4:
r − c diagonal and r + c anti-diagonal are all unused. For n = 4, exactly these two boards survive.