Sub topic 11
Solving N-Queens
This chapter assumes you already know the choose-explore-unchoose template and how pruning cuts off hopeless branches. It also assumes you can read Python sets and nested loops.
The Problem
The task is 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. The goal is to count every valid arrangement. For n = 8 there are 92 of them.
Brute force would try every way to put 8 queens on 64 squares, which is about 4.4 billion placements. Backtracking with pruning explores only a few thousand partial boards.
Shaping the State-Space Tree
There can be only one queen per row, so the first design decision is to place queens row by row. Each level of the tree is one row, and each branch is a choice of column. This rule removes row conflicts before any check runs.
The remaining conflicts are columns and diagonals. Each one can be identified by a single number:
| Line | Key that stays constant along it |
|---|---|
| Column | `col` |
| Down-right diagonal | `row - col` |
| Down-left diagonal | `row + col` |
You can store these keys in three sets. Then "is this square attacked?" becomes three set lookups, which take constant time. You don't need to scan the board.
The Solver
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 continue line does the pruning. If a square is attacked, the solver never builds the subtree below it. When row == n, every row holds a queen and no attack was ever allowed, so the board is a valid solution.
Watching a Branch Die
The tree below traces n = 4 with the first queen at column 0. Every path under that choice runs out of safe squares, so the solver unwinds and tries column 1 next.
Common Errors
- Forgetting one of the removals. If you undo
colsbut notdiag2, later branches see phantom attacks and the count comes out too low. - Using
abs(row - col)as the diagonal key. That merges different diagonals. For example, (0, 1) and (1, 0) both give 1 even though they sit on different down-right diagonals. Use the signed difference. - Storing the board as a 2D grid and scanning it. The result is still correct, but each check costs O(n) instead of O(1).
Exercise
What does n_queens(4) return? Using the diagram, explain why no solution puts the row 0 queen in column 0.
Show answer
It returns 2. The solutions, written as the column for each row, are [1, 3, 0, 2] and [2, 0, 3, 1]. With a queen at (0, 0), row 1 can only use column 2 or 3. Column 2 leaves no safe square in row 2. Column 3 allows (2, 1), but then every square in row 3 is attacked. Every branch is pruned before it reaches row == n.
Exercise
Why does the solver never need to check whether two queens share a row?
Show answer
Each call places exactly one queen in row row and then moves to row + 1. The structure of the tree makes a row conflict impossible.