N-Queens
Place n queens on an n x n chessboard so that no two queens attack each other. A queen attacks every square in its row, its column and both of its diagonals.
Return every distinct arrangement. Write each board as a list of n strings, one per row, where "Q" marks a queen and "." marks an empty square. The boards can be in any order.
Example 1
Input: n = 4 Output: [[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]
A 4 x 4 board has exactly two arrangements, and each is the mirror image of the other.
Example 2
Input: n = 3 Output: []
No arrangement works on a 3 x 3 board.
Constraints
1 <= n <= 9
Approach
Trying every set of n squares is hopeless even for small boards. Two observations shrink the search. Every row needs exactly one queen, so you only choose a column for each row. And as soon as a partial board has two queens attacking each other, no way of filling the remaining rows can fix it, so that branch can be abandoned immediately.
Place queens from the top row down. For each column in the current row, check whether it's attacked by a queen already placed. Three sets make the check O(1): used columns, used diagonals (row - col is constant along each one) and used anti-diagonals (row + col is constant along each one). If the square is safe, record it, recurse into the next row, then remove it from the sets before trying the next column. Reaching row n means every row has a queen, so build the board strings and save them.
Steps
- Keep an array of the queen's column in each row and three sets for used columns, diagonals and anti-diagonals.
- In
place(row), ifrow == n, convert the columns into board strings and save them. - Otherwise, for each column, skip it if its column, diagonal or anti-diagonal is in use.
- Mark the square, call
place(row + 1), then unmark it. - Start with
place(0)and return every saved board.
from typing import List
def solve_n_queens(n: int) -> List[List[str]]:
solutions = []
queen_col = [0] * n # queen_col[row] = column of the queen placed in that row
used_cols, used_diags, used_anti = set(), set(), set()
def place(row):
if row == n:
solutions.append(["." * c + "Q" + "." * (n - c - 1) for c in queen_col])
return
for col in range(n):
# Squares on one diagonal share row - col; on one anti-diagonal, row + col.
if col in used_cols or row - col in used_diags or row + col in used_anti:
continue
queen_col[row] = col
used_cols.add(col)
used_diags.add(row - col)
used_anti.add(row + col)
place(row + 1)
used_cols.remove(col) # undo the choice before trying the next column
used_diags.remove(row - col)
used_anti.remove(row + col)
place(0)
return solutionsComplexity
- Time:
O(n!). The first row hasnchoices, the next at mostn - 1and so on, and building each board addsO(n^2). - Space:
O(n)for the recursion and the sets, not counting the output.
Common mistakes
- Checking only columns and forgetting one of the two diagonal directions.
- Forgetting to remove a queen from the sets after the recursive call returns, which blocks squares that should be free.
- Saving a reference to a board that keeps changing instead of building a fresh copy for each solution.