Pruning: stopping a branch early
1 Most boards are wrong
The N-Queens puzzle asks us to place n queens on an n × n chessboard so that no two attack each other. A queen attacks along its row, its column and both of its diagonals.
Two queens in one row always attack, so each row holds exactly one queen. The search chooses a column for row 0, then for row 1, and so on. This is the choose, explore, undo walk from the backtracking lesson, with one level of the decision tree per row.
On a 4 × 4 board, every row has 4 columns to choose from. The tree ends in 4⁴ = 256 full boards, and only 2 of them are valid. At n = 8 it ends in about 1.7 × 10⁷ boards, for 92 answers.
A gardener does not wait for a dead branch to grow leaves. They cut it where it starts, and everything that would have grown from it goes too. In a search, that cut is pruning: a check that stops a branch as soon as its choices so far cannot lead to an answer.
2 Check when you choose, not at the leaf
Plain backtracking fills every row first and checks the full board at the leaf. Its first two choices on the 4 × 4 board are column 0 for row 0, then column 0 for row 1. These two queens already attack each other. The search does not know it yet. It fills rows 2 and 3 in all 4 × 4 = 16 ways, and rejects all 16 boards at the leaf.
The pruned search checks a square when it chooses it. An attacked square is skipped, so the call for it never happens and nothing below it is built:
place(row)
if row == n
count one answer
return
for col from 0 to n - 1
if square (row, col) is attacked
skip it (the cut)
choose: put a queen at (row, col)
explore: place(row + 1)
undo: take the queen off
The check before choose is the only new line. It is safe because adding queens never removes an attack. A board with a clash stays wrong, whatever we add to it.
A cut near the trunk takes more of the tree than a cut near a leaf. On a 4 × 4 board, a cut at row 1 removes 16 boards. On an 8 × 8 board, a cut at row 1 removes 8⁶ boards, about 2.6 × 10⁵.
3 Four queens by hand
The steps below run the pruned search on the 4 × 4 board. Blue squares hold queens, and crossed squares are attacked. An orange row has no safe square left: it is a dead end, and the search goes back up.
The search does not stop at the first answer, because the puzzle asks for all of them. Each row of the table is one path from the top of the tree, with the queen's column in each row:
| Row 0 | Row 1 | Row 2 | Row 3 | Result |
|---|---|---|---|---|
| 0 | 2 | dead end at row 2 | ||
| 0 | 3 | 1 | dead end at row 3 | |
| 1 | 3 | 0 | 2 | answer |
| 2 | 0 | 3 | 1 | answer |
| 3 | 0 | 2 | dead end at row 3 | |
| 3 | 1 | dead end at row 2 |
Drawn as a tree, this is all that is left after the cuts. Each level is a row, and each number is a column:
The search places only 16 queens. The tree without cuts has 340 nodes under its top. The second answer, columns 2, 0, 3, 1, is the first one seen in a mirror.
The gap grows fast with n. We ran the search with and without the cuts, and counted the calls to place:
| n | Calls without cuts | Calls with cuts | Answers |
|---|---|---|---|
| 4 | 341 | 17 | 2 |
| 6 | about 56,000 | 153 | 4 |
| 8 | about 1.9 × 10⁷ | about 2,000 | 92 |
| 10 | about 10¹⁰ | about 36,000 | 724 |
| 12 | about 10¹³ | about 860,000 | about 14,000 |
4 Columns and diagonals in one step
The code needs a test for an attacked square. Rows need none, since each row gets one queen. Scanning the queens above would cost O(n) per square. Three arrays of flags answer in one step instead:
- Columns.
cols[c]is true when column c has a queen. - Down-right diagonals. Along one, the row and the column both go up by 1, so r − c stays the same. These flags are
diags. - Down-left diagonals. Along one, the row goes up by 1 and the column goes down by 1, so r + c stays the same. These flags are
antiDiags.
Each diagonal has its own number, so it gets one flag. The sum r + c runs from 0 to 2n − 2, which needs 2n − 1 flags. The difference r − c runs from −(n − 1) to n − 1, but an array has no negative index. Adding n − 1 shifts it to 0 to 2n − 2, so the flag sits at diags[r - c + n - 1].
A square is safe when all three flags are false. Step 2 of the trace shows why (1, 1) was attacked: the queen at (0, 0) has r − c = 0, and so does (1, 1). Choose sets the three flags, and undo clears the same three.
5 The code and its cost
N-Queens II asks only how many valid boards there are, so place(row) returns a count. It is the number of ways to finish the board from that row down.
C++
place is an inner function. It changes items of cols, diags and anti_diags, never the names themselves, so it needs no nonlocal.
Declare place before you set it. The var place func(row int) int line comes first, so the function can call itself.
Keep the index from going below 0. row - col underflows a usize when col is bigger, so the code adds n − 1 first: row + self.n - 1 - col.
It returns 2 for n = 4, 4 for n = 6 and 92 for n = 8. For n = 2 it returns 0, because no two squares on that board are safe from each other.
N-Queens wants the boards themselves. For that, we also keep each row's column in a list, and turn the list into strings when row reaches n.
The cuts slow the growth down, but the time is still exponential. The column check alone leaves row r at most n − r columns, so there are at most n! full boards. That gives the usual bound, O(n!). The diagonals cut most of those too, yet every extra row still multiplies the work.
The space is O(n): three arrays of about 2n flags, and at most n calls on the stack.
6 Three kinds of cut
N-Queens uses one kind of cut. The problems in this section use three.
- Feasibility: the choices so far break a rule. Two queens attack, or a digit repeats in a sudoku row. No later choice can repair it. The
usedarray in Permutations was a cut of this kind. - Bound: the choices so far can no longer reach the goal. Combination Sum allows a choice only while the sum stays within the target. With the values sorted, one value past the target means every later value is past it too. So the loop can
breakinstead ofcontinue. - Early exit: one answer is enough. When the problem wants one filled board or a yes or no, the call returns true as soon as it finds an answer. Each caller sees the true and returns it at once, without trying its other choices.
Here is the bound at work. Combination Sum with [2, 3, 5] and target 8 reaches the state [2, 2, 2], with a sum of 6:
The value 5 is never tried, and neither is anything that would grow from it.
The problems in this section each need one or two of these cuts:
| Problem | What cuts a branch |
|---|---|
| N-Queens | a column or diagonal is taken |
| Sudoku Solver | the digit is in the row, column or box; stop at the first full board |
| M-coloring | a neighbour already has this colour |
| Rat in a maze | a wall, or a cell already on the path |
| Word Search | the letter does not match; stop when the word is found |
| Word Break II | the next piece is not in the dictionary |
7 Searching a grid
Word Search gives a grid of letters and a word. The word must be spelled by moving up, down, left or right, using each cell at most once. Here the choices are the four neighbours, and the state is the path so far.
A neighbour is cut before the call goes into it when it is off the grid, already on the path, or holds the wrong letter. The last cut does most of the work. A wrong first letter ends a start at once, so most cells cost one comparison.
The path needs a mark. We mark a cell as visited when it joins the path, and unmark it when the call returns. Unmarking is the undo: other paths may still need that cell.
At T the word is complete, so the call returns true, and every call above it returns true at once. That is the early exit.
8 Mistakes
- A cut that is not safe. A cut may only remove branches with no answer below them. A
breakon unsorted values is the usual slip. With [5, 3, 2] and target 8, the branch [5] tries 5 again, goes past 8 and breaks, so 3 is never tried. The search finds only [2, 2, 2, 2], and misses [3, 5] and [2, 3, 3]. - Checking only at the leaf. The answer is right, but nothing is cut. At n = 10 that is about 10¹⁰ calls, far past the time limit, so it gets TLE.
- Half an undo. If undo clears
colsbut not the two diagonal arrays, n = 4 returns 0 instead of 2. In a grid, a cell left marked blocks every later path through it. - No mark at all. TENET is not in the grid above, but without marks the search finds it: T, E, N, then back to the same E and the same T.
- The diagonal offset. With r − c alone, square (0, 1) gives the index −1, and the array starts at 0.
Practice it
- Word SearchMedium
- N-QueensHard
- Sudoku SolverHard
- Rat in a mazeHard
- M-coloringHard
- Beautiful ArrangementMedium
- Word Break IIHard
- Expression Add OperatorsHard
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.