Description
Place n queens on an n x n board so no two share a row, column, or diagonal. Return all valid boards as strings with Q for queens and dots for empty cells.
Solution
def solve_n_queens(n):
columns, down, up = set(), set(), set()
placements, result = [], []
def visit(row):
if row == n:
result.append(["." * col + "Q" + "." * (n - col - 1) for col in placements])
return
for col in range(n):
if col in columns or row - col in down or row + col in up:
continue
columns.add(col)
down.add(row - col)
up.add(row + col)
placements.append(col)
visit(row + 1)
placements.pop()
columns.remove(col)
down.remove(row - col)
up.remove(row + col)
visit(0)
return resultExamples
Example 1
- Input
[1]- Output
[["Q"]]
One queen fits the one-cell board.
Example 2
- Input
[2]- Output
[]
Every pair of placements conflicts.
Example 3
- Input
[4]- Output
[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Exactly two four-queen boards exist.
Approach
Place one queen per row, tracking occupied columns and the two diagonal identifiers row - column and row + column. Backtrack only through unoccupied choices and construct a board for every complete placement.
Time & space
O(n n!) search time plus O(S n^2) to emit S boards; O(n) auxiliary space excluding output.