Construct Non-Conflicting Queens Configurations
Trees & GraphsModel answerLast updated
Compute all possible configurations of n non-attacking queens on an n x n board using stateful depth-first search.
Given an integer n specifying the dimensions of an n × n grid, place n queens on the board such that no queen can attack any other.
In chess, a queen can move any number of squares horizontally, vertically, or diagonally. Thus, a placement is non-attacking if no two queens share a row, column, or diagonal.
Return every unique arrangement of the board that satisfies this condition.
- Represent each configuration as a list of
nstrings. - Each string corresponds to a single row, where
'Q'denotes a queen and'.'denotes an open space. - The output can list the arrangements in any order.
Constraints:
1 <= n <= 9
Example 1:
Input: n = 4
Output:
[
[".Q..",
"...Q",
"Q...",
"..Q."],
["..Q.",
"Q...",
"...Q",
".Q.."]
]
Example 2:
Input: n = 1
Output:
[["Q"]]
Hints
Hint 1
Since exactly one queen must go in every row, iterate through the board row by row rather than evaluating all n^2 positions at once.
Hint 2
How can you efficiently check if a candidate column or diagonal is already under attack in O(1) time?
Hint 3
Notice the properties of matrix indices: elements along the same main diagonal share the same difference (row - col), while elements on the same anti-diagonal share the same sum (row + col).
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Backtracking with State Tracking
A naive search over an $n \times n$ grid would involve selecting $n$ cells out of $n^2$, leading to an immense search space. However, because no two queens can inhabit the same row, a valid configuration must place exactly one queen per row.
We can structure our search row by row, starting from index 0 down to n - 1. For each row, we try placing a queen in column c (from 0 to n - 1), verifying whether (row, c) is under attack by any previously placed queen.
To achieve $O(1)$ safety checks, we maintain state tracking for used paths:
- Columns: Tracked via a set of column indices
c. - Main Diagonals ($\searrow$): All cells on the same main diagonal share an identical difference
row - col. - Anti-Diagonals ($\swarrow$): All cells on the same anti-diagonal share an identical sum
row + col.
Algorithm Steps
- Maintain an array
queensof size $n$, wherequeens[r]holds the column index of the queen in rowr. - Track occupied columns, main diagonals, and anti-diagonals using hash sets or boolean arrays.
- Define a recursive helper function
backtrack(row):- Base Case: If
row == n, all queens have been safely placed. Construct the string grid representation and add it to the final result set. - Recursive Case: Loop through each column
cfrom0ton - 1.- Check if
c,row - c, orrow + cexist in our tracking sets. If any do, skip to the next column. - Add the indicators to the tracking sets and update
queens[row] = c. - Recurse onto
backtrack(row + 1). - Revert state modifications (remove from tracking sets) to explore subsequent candidates.
- Check if
- Base Case: If
Python Code
from typing import List
def solve_n_queens(n: int) -> List[List[str]]:
results = []
# queens[r] stores the column index for the queen in row r
queens = [-1] * n
# State tracking for O(1) lookup
used_cols = set()
used_main_diags = set() # row - col
used_anti_diags = set() # row + col
def construct_board() -> List[str]:
board = []
for r in range(n):
c = queens[r]
board.append("." * c + "Q" + "." * (n - c - 1))
return board
def backtrack(r: int) -> None:
if r == n:
results.append(construct_board())
return
for c in range(n):
main_diag = r - c
anti_diag = r + c
if c in used_cols or main_diag in used_main_diags or anti_diag in used_anti_diags:
continue
# Place queen and record conflict zones
queens[r] = c
used_cols.add(c)
used_main_diags.add(main_diag)
used_anti_diags.add(anti_diag)
backtrack(r + 1)
# Backtrack state
used_cols.remove(c)
used_main_diags.remove(main_diag)
used_anti_diags.remove(anti_diag)
backtrack(0)
return results
Complexity Analysis
-
Time Complexity:
- The upper bound for valid leaf nodes searched is $O(n!)$ because each row has at most $n - r$ valid choices remaining.
- Generating each string output board takes $O(n^2)$ work at every valid solution leaf.
- Overall Time Complexity: $O(n! + S \cdot n^2)$, where $S$ is the total count of valid board arrangements (e.g., $S = 352$ for $n = 9$).
-
Space Complexity:
- $O(n)$ auxiliary space for storing the recursion call stack, the internal
queensplacement array, and conflict tracking sets. - Output space requires $O(S \cdot n^2)$ to store all valid configurations.
- $O(n)$ auxiliary space for storing the recursion call stack, the internal