N-Queens
N-Queens is LeetCode 51 (Hard). Place n queens on an n × n chessboard so that no two queens attack each other: no two may share a row, a column or a diagonal.
- Return every valid board.
- Each board is a list of
nstrings, with'Q'for a queen and'.'for an empty square.
The classic 8 queens problem is the case n = 8. With n at most 9 the number of boards stays small, but trying every placement of n queens on n² squares does not, so the search must cut off bad branches early.
- 1 <= n <= 9
Intuition
Since no two queens can share a row, every valid board has exactly one queen in each row. So build the board row by row: in each row, try each column, and go on to the next row only if that square is safe.
- Fast safety check: squares on one down-right diagonal share the same
row − col, and squares on one up-right diagonal share the samerow + col. Three sets (columns,row − colvalues,row + colvalues) answer "is this square attacked?" in O(1). - Backtracking: when a row has no safe square, the queen above it is in a bad spot. Remove it, un-mark its lines, and try that row's next column.
Reaching row n means every row holds a safe queen, so the board is saved.
Build an arrangement one choice at a time, where each choice rules out later ones and all valid arrangements are wanted: that is backtracking. Sudoku Solver and Permutations follow the same place, recurse, undo rhythm.
Approach
Before reading on, write the row − col and row + col values on a 4 × 4 grid and check that each diagonal shares one value. Aim for a search that never places two queens in one row.
Fill one row per call
Write place(row), which puts a queen somewhere in row and then calls place(row + 1). Choosing one square per row makes row clashes impossible, so only columns and diagonals need checking.
Skip attacked squares
For each col in the row, skip it if col is in the column set, row − col is in the down-diagonal set, or row + col is in the up-diagonal set. Any of those means an earlier queen already covers that square.
Place, recurse, then undo
On a safe square, add its three values to the sets, write 'Q' into the grid, and call place(row + 1). When the call returns, remove the three values and reset the square to '.', so the next column starts from the same board.
Save a copy at row n
When row == n, all rows hold a queen that no other queen attacks. Turn each grid row into a string and append the copy to the answer, because the grid itself keeps changing.
Code in Python, C++ and Java
Common pitfalls
Indexing an array with row − col
downs = [False] * n if downs[row - col]: ...
downs = [False] * (2 * n - 1) if downs[row - col + n - 1]: ...
row − col runs from −(n − 1) to n − 1, which is 2n − 1 values. In C++ or Java a negative index crashes or reads the wrong memory; in Python downs[-1] silently reads the last slot, so for n = 4 the square (0, 1) and the square (3, 0) share a flag and valid boards get rejected. Shift by n − 1 and size the array 2n − 1.
Building the grid with list multiplication
grid = [["."] * n] * n
grid = [["."] * n for _ in range(n)]
The outer * n repeats one inner list n times. Writing a queen into row 0 writes it into every row, so for n = 4 the saved boards contain columns full of 'Q'.
Saving the grid instead of a copy
boards.append(grid)
boards.append(["".join(r) for r in grid])
Every saved entry points at the same grid, which the undo step wipes back to dots. For n = 4 the result holds two all-dot boards instead of the two solutions.
Edge cases
No arrangement works, and the search returns an empty list after trying every first-row column.
One queen on one square is valid, so the answer is [["Q"]].
Complexity
n choices, row 1 at most n − 1 safe columns, and so on, so the search tree has at most about n! leaves; each check is O(1) and copying a board costs O(n²). The grid takes O(n²) space, the sets and the call stack O(n), not counting the returned boards.N-Queens FAQ
How many solutions does the 8 queens problem have?
92 boards. Many are rotations or mirror images of each other; grouping those together leaves 12 truly different solutions. For n from 1 to 9 the counts are 1, 0, 0, 2, 10, 4, 40, 92 and 352.
What if I only need the number of boards?
That is N-Queens II (LeetCode 52). Use the same search but add 1 at row == n instead of building strings. Replacing the three sets with bitmasks of taken columns and diagonals makes it faster still.
Is there a way to place n queens without searching?
Yes, for a single board. Explicit patterns exist for every n ≥ 4 (for example, rules based on n mod 6 that list the column for each row). They give one valid board in O(n), but not all of them, so this problem still needs backtracking.