Sub topic 11
Solving N-Queens
The N-Queens problem asks you to place N queens on an N×N chessboard so that no two queens attack each other. A queen attacks along its row, its column, and both diagonals. For N = 8 there are 92 solutions. For N = 2 and N = 3 there are none.
This chapter assumes you already know the choose-explore-unchoose template, how to restore state after a recursive call, and the basic idea of pruning from earlier chapters. You should be comfortable with Python sets and with nested loops over a 2D grid.
Why N-Queens Is a Good Backtracking Problem
A brute-force search would try every way to put N queens on N² squares. For N = 8 that is C(64, 8), about 4.4 billion placements, and each one has to be checked afterwards. Backtracking reduces this in two ways:
- The choices are structured. Two queens in the same row always attack each other, so every valid solution has exactly one queen per row. Placing queens row by row makes the row constraint impossible to break.
- Each choice is checked right away. When you place a queen in row
r, you check it against the queens already in rows0tor - 1. If the square is attacked, that whole subtree is skipped.
The first point changes the shape of the state-space tree. It now has depth N, and each level has at most N branches. The second point prunes most of that tree.
Encoding the Constraints
The safety check has to answer one question quickly: is square (row, col) attacked by any queen already placed? Three facts give an answer in constant time.
| Attack line | Invariant along the line | Range of values | Number of lines |
|---|---|---|---|
| Column | `col` | `0` to `n - 1` | n |
| Main diagonal (top-left to bottom-right) | `row - col` | `-(n - 1)` to `n - 1` | 2n − 1 |
| Anti-diagonal (top-right to bottom-left) | `row + col` | `0` to `2n - 2` | 2n − 1 |
Moving one step down-right adds 1 to both row and col, so row - col stays the same. Moving one step down-left adds 1 to row and subtracts 1 from col, so row + col stays the same. Each diagonal therefore has a single integer that identifies it.
Keep one set for each kind of line. A square is safe only if its column, its row - col value, and its row + col value are all missing from their sets.
Counting Solutions
Here is the full counting solver. It follows the template: choose a column, record it in all three sets, explore the next row, then remove it from all three sets.
def n_queens(n):
cols, diag1, diag2 = set(), set(), set()
count = 0
def backtrack(row):
nonlocal count
if row == n:
count += 1
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)
backtrack(row + 1)
cols.remove(col)
diag1.remove(row - col)
diag2.remove(row + col)
backtrack(0)
return count
print(n_queens(8)) # 92The base case row == n means every row has a queen and every placement passed the safety check. No final validation is needed, because invalid states were never built.
Tracing a Small Board
The 4×4 board is small enough to trace by hand. With column 0 in row 0, every continuation dies by row 2 or row 3. The search backtracks to row 0 and tries column 1, which leads to the first solution.
The branches [0,0] and [0,1] don't appear in the tree at all. The safety check rejects them inside the loop before any recursive call happens. That is pruning at work: rejected children cost one set lookup each and are never expanded.
Returning the Actual Boards
Counting is enough for benchmarks. Usually you want the placements themselves. Keep a queens list where queens[row] is the column of the queen in that row, and convert it to strings when you reach a solution.
def solve_n_queens(n):
cols, diag1, diag2 = set(), set(), set()
queens = []
solutions = []
def backtrack(row):
if row == n:
board = ['.' * c + 'Q' + '.' * (n - c - 1) for c in queens]
solutions.append(board)
return
for col in range(n):
if col in cols or (row - col) in diag1 or (row + col) in diag2:
continue
queens.append(col)
cols.add(col)
diag1.add(row - col)
diag2.add(row + col)
backtrack(row + 1)
queens.pop()
cols.remove(col)
diag1.remove(row - col)
diag2.remove(row + col)
backtrack(0)
return solutions
for board in solve_n_queens(4):
print('\n'.join(board))
print()
# .Q..
# ...Q
# Q...
# ..Q.
#
# ..Q.
# Q...
# ...Q
# .Q..The board strings are new objects built at the moment the solution is found, so later queens.pop() calls can't change them. If you appended queens itself, every saved entry would point to the same list, and that list ends up empty.
Common Errors
- Forgetting one of the three removals. If
diag2.remove(...)is missing, a diagonal stays blocked after its queen is gone. The solver then silently undercounts. For N = 8 you might get a number like 0 or 4 and no error message. - Using the wrong diagonal key. Keys like
row * colorabs(row - col)merge diagonals that are actually different.absmergesrow - col = 2withrow - col = -2, which are separate lines. - Putting both diagonal kinds in one set.
row - col = 2androw + col = 2are different lines, but in a shared set they collide. Use two sets, or offset one key (for examplerow - col + nandrow + col + 3 * n). - Checking the whole board on every placement. Scanning all earlier queens works, but it costs O(row) per check instead of O(1). This is fine for N = 8 and slow for N = 14.
- Checking safety in the base case. If you place queens freely and validate only at depth N, you lose all pruning and enumerate N^N leaves.
A Faster Variant: Bitmasks
For larger N, you can replace the sets with integers whose bits mark occupied columns and diagonals. Shifting the diagonal masks by one bit per row moves each diagonal's "shadow" into the right position on the next row.
def n_queens_bits(n):
full = (1 << n) - 1
def place(cols, d1, d2):
if cols == full:
return 1
count = 0
free = full & ~(cols | d1 | d2)
while free:
bit = free & -free # lowest free column
free -= bit
count += place(cols | bit,
((d1 | bit) << 1) & full,
(d2 | bit) >> 1)
return count
return place(0, 0, 0)
print(n_queens_bits(8)) # 92
print(n_queens_bits(10)) # 724This version has no unchoose step. The state is passed by value as immutable integers, so each call gets its own copy and there is nothing to restore. That works when the state is small enough to copy cheaply. For larger state, such as a Sudoku board, mutating in place and undoing is usually the better trade.
Edge Cases and Growth
| n | Solutions |
|---|---|
| 1 | 1 |
| 2 | 0 |
| 3 | 0 |
| 4 | 2 |
| 5 | 10 |
| 6 | 4 |
| 7 | 40 |
| 8 | 92 |
| 9 | 352 |
| 10 | 724 |
The counts don't grow smoothly. N = 6 has fewer solutions than N = 5. The solver handles N = 0 by returning 1, because the empty board is one valid arrangement. Decide whether that matches what your caller expects.
Finding one solution is much easier than counting all of them. Constructive formulas place queens directly for any N ≥ 4, so you don't need search for that case. Backtracking is the right tool when you need every solution, or when extra constraints (such as pre-placed queens or blocked squares) break the formulas.
Exercises
Exercise
Why does n_queens(3) return 0? Trace the search briefly.
Show answer
If the row-0 queen is in a corner (column 0 or 2), it attacks every square in row 1 except the opposite corner. A queen there then attacks the whole of row 2. If the row-0 queen is in the middle (column 1), it attacks all three squares in row 1. Every branch dies before row 2 is filled, so no leaf at depth 3 is reached.
Exercise
You remove the diag1 and diag2 checks and keep only the column set. What does n_queens(n) now count, and what does it return for n = 4?
Show answer
It counts placements with one queen per row and per column, ignoring diagonals. These are the permutations of the columns, so it returns n!, which is 24 for n = 4.
Exercise
The board is symmetric under left-right reflection. Change n_queens so it only tries columns 0 to n//2 - 1 in row 0, doubles the result, and handles odd n correctly. Why does odd n need special care?
Show answer
For even n, each solution with its first queen in the left half has a mirror image with its first queen in the right half, so count the left half and double it. For odd n, the middle column (n // 2) is its own mirror. Count the left-half columns and double that, then run the search once more with the row-0 queen fixed at column n // 2 and add that count without doubling. One way to do this is to give backtrack a parameter that limits the columns tried in row 0, and leave every other row unrestricted.
Exercise
Squares (1, 3) and (3, 1) on an 8x8 board: do queens there attack each other? Use the diagonal keys to decide.
Show answer
Yes. Both squares have row + col = 4, so they lie on the same anti-diagonal. Their row - col values are -2 and 2, which differ, so they are not on the same main diagonal. One shared line is enough for an attack.