Pruning: stopping a branch early

Video lessonComing soon

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.

Placing four queens, row by row
Q
Row 0: queen at column 0

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 0Row 1Row 2Row 3Result
02dead end at row 2
031dead end at row 3
1302answer
2031answer
302dead end at row 3
31dead 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:

02"02"31"031"1302"1302"2031"2031"302"302"1"31"
The whole pruned search for n = 4. A ringed node ends a path, and the blue path is the first answer

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:

nCalls without cutsCalls with cutsAnswers
4341172
6about 56,0001534
8about 1.9 × 10⁷about 2,00092
10about 10¹⁰about 36,000724
12about 10¹³about 860,000about 14,000
n = 8, no cuts1.9 × 10⁷n = 8, cuts2000n = 12, no cuts9.7 × 10¹²n = 12, cuts8.6 × 10⁵about 1 second
Calls to place, on a scale where each mark is ten times the last

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.
0-1-2-310-1-2210-13210
r − c: one value per down-right diagonal
0123123423453456
r + c: one value per down-left diagonal

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.

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 used array 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 break instead of continue.
  • 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:

203152
Sum 6 so far: 2 reaches 8, 3 goes past it, so the loop stops

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:

ProblemWhat cuts a branch
N-Queensa column or diagonal is taken
Sudoku Solverthe digit is in the row, column or box; stop at the first full board
M-coloringa neighbour already has this colour
Rat in a mazea wall, or a cell already on the path
Word Searchthe letter does not match; stop when the word is found
Word Break IIthe 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.

Finding RENT
CATSOREDDENT
C, A, T, S and O are not R. R matches

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 break on 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 cols but 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.
Before writing a cut, ask one question: could any later choice still turn this branch into an answer? If not, cut it at the choose step. If maybe, keep it.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.