本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 1 · 本科一年级
20Exhaustive Search and Backtracking
A sudoku that a puzzle page calls diabolical takes a person an evening. A program of forty lines solves it in a few hundred steps, with no cleverness about sudoku at all: it fills an empty cell with a digit that breaks no rule, goes on, and when it gets stuck it takes back its last choice and tries the next one. That method, backtracking, solves many problems that have no better known algorithm: puzzles, schedules, colourings, selections under a budget. Its cost can be enormous; this chapter shows how to organise the search so that most of it is never done.
You already know
There are subsets of an -element set, orders of elements and subsets of elements. Recursive functions and their termination were studied in Chapter 11.
20.1 Enumerating
Definition 20.1 (Exhaustive search)
An exhaustive search, or brute force, solves a problem by generating every candidate solution and testing each.
The candidates are usually subsets, orders or selections, and the first task is to generate them all, each once. Subsets of items correspond to the integers from 0 to by their binary digits; they also come from a recursion that decides the first item, in or out, then the rest.
def subsets_binary(items):
"""Subset number x holds items[i] exactly when bit i of x is 1."""
n = len(items)
for x in range(2**n):
yield [items[i] for i in range(n) if x >> i & 1]
def subsets(items, chosen=()):
"""The include/exclude tree: decide items[0], then the rest."""
if not items:
yield list(chosen)
return
yield from subsets(items[1:], chosen + (items[0],)) # with items[0]
yield from subsets(items[1:], chosen) # without it
Orders are generated by putting each remaining element in the first free position, in turn, and ordering the rest; swapping the candidate into place, and back afterwards, does it in the array itself. The lexicographic successor computes the next order directly: find the longest decreasing suffix, exchange the element just before it with the smallest larger element of the suffix, and reverse the suffix.
def permutations(a, k=0):
"""All orders of a[k:], by swapping each candidate into position k in turn."""
if k == len(a):
yield list(a)
return
for i in range(k, len(a)):
a[k], a[i] = a[i], a[k]
yield from permutations(a, k + 1)
a[k], a[i] = a[i], a[k] # undo, so that a[k:] is as before
def next_permutation(a):
"""The next order of a in lexicographic order, in place; False after the last."""
i = len(a) - 2
while i >= 0 and a[i] >= a[i + 1]:
i -= 1 # a[i+1:] is decreasing: the last order of its elements
if i < 0:
return False
j = len(a) - 1
while a[j] <= a[i]:
j -= 1 # the smallest element of a[i+1:] larger than a[i]
a[i], a[j] = a[j], a[i]
a[i + 1:] = reversed(a[i + 1:]) # the first order of the suffix
return True
$ python enumerate.py
subsets by bits: ['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
subsets by tree: ['abc', 'ab', 'ac', 'a', 'bc', 'b', 'c', '']
permutations : ['abc', 'acb', 'bac', 'bca', 'cba', 'cab']
lexicographic : 24 orders, ['abcd', 'abdc', 'acbd', 'acdb'] ... dcba
2 of abcd : ['ab', 'ac', 'ad', 'bc', 'bd', 'cd']
counts : subsets of 10: 1024 orders of 8: 40320 4 of 10: 210
Each generator spends a bounded amount of work per node of its tree, and its tree has a number of nodes proportional to the number of outputs, times at most: the cost is proportional to the output, which is all one can ask. The output itself is the problem: subsets is a billion, and orders is more than a trillion.
20.2 The tree of partial solutions
Definition 20.2 (Partial solution, tree of partial solutions, backtracking)
A partial solution is a sequence of choices that a complete solution may extend. The tree of partial solutions has the empty sequence as its root, and as children of a node its extensions by one choice. Backtracking explores this tree depth first, abandoning a node, and its whole subtree, as soon as the partial solution cannot be extended into a valid one.
Definition 20.3 (Constraint, pruning)
The constraints of a problem are the conditions a solution must satisfy. Pruning is abandoning a node because its partial solution already breaks a constraint, or cannot lead to a solution better than one already known.
An exhaustive search tests the constraints at the leaves only; backtracking tests them as early as possible. The difference is the number of nodes visited. The method itself is short, once the problem supplies its choices and its tests:
def backtrack(partial, choices, is_valid, is_complete, found):
"""Extend `partial` in every way that stays valid; report every complete one."""
if is_complete(partial):
found(list(partial))
return
for c in choices(partial):
partial.append(c)
if is_valid(partial): # prune: no completion of an invalid partial solution
backtrack(partial, choices, is_valid, is_complete, found)
partial.pop() # undo the choice
Its demonstration builds the words of three letters over a, b with no two equal neighbours; the test on the last two letters prunes every other branch at each level.
$ python backtrack.py
['aba', 'bab']
20.3 Pruning: the queens
Place queens on an chessboard so that no two attack each other: no two on a row, a column or a diagonal. One queen goes on each row, so a placement is the list of the columns of rows ; the columns must be distinct, and two queens at and share a diagonal when or . Sets of the used columns and diagonals make each test .
def solve(n):
"""(solutions, nodes): the tree of partial solutions, pruned at the first attack."""
cols, diag1, diag2 = set(), set(), set() # used columns and diagonals
count = [0, 0] # solutions, nodes
def place(r):
count[1] += 1
if r == n:
count[0] += 1
return
for c in range(n):
if c in cols or r - c in diag1 or r + c in diag2:
continue # attacked: this branch is pruned
cols.add(c), diag1.add(r - c), diag2.add(r + c)
place(r + 1)
cols.remove(c), diag1.remove(r - c), diag2.remove(r + c)
place(0)
return count[0], count[1]
$ python queens.py
n solutions nodes, pruned nodes, full tree ratio
4 2 17 65 3.8
5 10 54 326 6.0
6 4 153 1957 12.8
7 40 552 13700 24.8
8 92 2057 109601 53.3
9 352 8394 986410 117.5
10 724 35539 9864101 277.6
Pruning does not change the exponential growth, but it changes its rate, and that decides which sizes are reachable. The tree without pruning has nodes (Exercise 20.9).
20.4 Sudoku and subset sum
Which choice to make first matters as much as when to test. In a sudoku, each empty cell can take the digits absent from its row, its column and its box. Choosing the cell with the fewest candidates makes dead ends appear early, near the root, where abandoning a node discards a large subtree; a cell with a single candidate costs no branching at all.
def candidates(g, i):
"""The digits that cell i can take: none of its row, column or 3 x 3 box."""
r, c = divmod(i, 9)
br, bc = 3 * (r // 3), 3 * (c // 3)
seen = {g[9 * r + k] for k in range(9)} | {g[9 * k + c] for k in range(9)}
seen |= {g[9 * (br + a) + bc + b] for a in range(3) for b in range(3)}
return DIGITS - seen
def solve(g, stats, first_empty=False):
"""Fill g in place; True if solved. stats["nodes"] counts the calls."""
stats["nodes"] += 1
empty = [i for i in range(81) if g[i] == "."]
if not empty:
return True
if first_empty:
i = empty[0]
else: # the empty cell with the fewest candidates
i = min(empty, key=lambda j: len(candidates(g, j)))
for d in sorted(candidates(g, i)): # no candidate: a dead end, return False
g[i] = d
if solve(g, stats, first_empty):
return True
g[i] = "."
return False
The grid was made by a program of this chapter that fills a grid at random and removes clues as long as the solution stays unique (make_grid.py); a grid with a unique solution is what a puzzle page prints.
$ python make_grid.py
25 clues
2..7..5..
....8...2
681..5.3.
76.8....5
...9.1...
..4.5...7
..6...1..
8.5.9..6.
.........
$ python sudoku.py
first empty cell: solved True, 1244 nodes
most constrained cell: solved True, 359 nodes
243 769 581
957 183 642
681 245 739
769 824 315
538 971 426
124 356 897
496 532 178
815 497 263
372 618 954
The subset-sum problem asks for the subsets of given numbers with a given total: here, the reading lists of exactly 1000 pages from the library’s books. With positive values, two tests prune the include/exclude tree: a partial sum already above the target, and a partial sum that even all the undecided values cannot bring up to the target. Sorting the values in decreasing order makes the first test fire early.
def count(values, target, prune):
"""(solutions, nodes) of the include/exclude tree over values."""
if prune:
values = sorted(values, reverse=True) # large first: overshoot early
rest = [sum(values[i:]) for i in range(len(values) + 1)] # undecided values
stats = [0, 0]
def visit(i, total):
stats[1] += 1
if prune and (total > target or total + rest[i] < target):
return # too much already, or even all the rest cannot reach the target
if i == len(values):
stats[0] += total == target
return
visit(i + 1, total + values[i])
visit(i + 1, total)
visit(0, 0)
return stats[0], stats[1]
$ python subset_sum.py
n lists nodes, all nodes, pruned
12 3 8191 791
16 9 131071 3321
20 19 2097151 9535
24 31 33554431 14595
Both tests are sound only because the values are positive (Exercise 20.6): a pruning rule must never discard a subtree that holds a solution.
20.5 Branch and bound
The problems so far ask for all solutions, or one. An optimisation problem asks for the best: in the knapsack problem, items have weights and values, and the task is a set of items of total weight at most a capacity with the largest total value.
Definition 20.4 (Branch and bound, bounding function, continuous relaxation)
Branch and bound explores the tree of partial solutions of an optimisation problem, keeps the best complete solution found so far, and prunes a node when a bounding function shows that no completion of it can beat that solution. A continuous relaxation of a problem allows fractions where the problem requires whole choices; its optimum is at least the problem’s, and gives a bound.
For the knapsack, the relaxation allows a fraction of an item. Its optimum is easy: take the items in decreasing order of value per unit of weight, and a fraction of the first one that does not fit. A node whose value so far plus the relaxation’s optimum on the remaining items and room does not exceed the best known value is pruned (Exercise 20.11 proves that this is sound).
def relaxation(things, i, room):
"""The best value of things[i:] in `room` if fractions of items were allowed:
greedy by value per unit of weight (things are sorted that way)."""
total = 0.0
for w, v in things[i:]:
if w <= room:
room, total = room - w, total + v
else:
return total + v * room / w # a fraction of the first item too big
return total
def best(things, capacity, bound):
things = sorted(things, key=lambda t: t[1] / t[0], reverse=True)
stats = {"best": 0, "nodes": 0}
def visit(i, room, value):
stats["nodes"] += 1
stats["best"] = max(stats["best"], value)
if i == len(things):
return
if bound and value + relaxation(things, i, room) <= stats["best"]:
return # no completion can beat the best solution found so far
w, v = things[i]
if w <= room:
visit(i + 1, room - w, value + v) # take item i
visit(i + 1, room, value) # leave it
visit(0, capacity, 0)
return stats["best"], stats["nodes"]
$ python knapsack_bb.py
n best nodes, backtracking nodes, branch and bound
8 312 337 12
12 460 5220 39
16 689 82103 41
20 836 1292056 92
figures/bb_tree.py). The first leaf reached, A and C, is the optimum; its value 65 then prunes both remaining branches. Counted as best counts them (a pruned node is visited, an item that does not fit is not tried), plain backtracking visits 20 nodes here and branch and bound 7.Plain backtracking only prunes items that do not fit, and its count doubles with each item; with the bound, the count barely grows here. These instances are friendly: on others the bound is weak and the search stays exponential. The knapsack has another method, by dynamic programming, in Chapter 23.
20.6 Exercises
Exercise 20.1 ★
In which order does subsets_binary("abcd") produce the subsets that contain d? And subsets("abcd")?
Solution
Solution of Exercise 20.1.
subsets_binary gives the subsets with d for the numbers 8 to 15, in this order: d, ad, bd, abd, cd, acd, bcd, abcd. The tree decides d last and includes before it excludes, so the subsets with d are every other leaf, starting with the first: abcd, abd, acd, ad, bcd, bd, cd, d.
Exercise 20.2 ★
Apply next_permutation to , giving each step.
Solution
Solution of Exercise 20.2.
The longest decreasing suffix is , so (). The smallest larger element of the suffix is 4, at . The exchange gives , and reversing the suffix gives .
Exercise 20.3 ★
Count the nodes of the queens search for in the figure, by level. How many leaves are dead ends?
Solution
Solution of Exercise 20.3.
Level by level: 1 (the root), 4, 6, 4 and 2: 17 nodes, as in Output 20.3. Four leaves are dead ends: 0 2, 0 3 1, 3 0 2 and 3 1.
Exercise 20.4 ★
For the subset sum of (sorted) with target 9, which node is pruned first, and by which test?
Solution
Solution of Exercise 20.4.
The remaining sums are . The root and the node “7 in” pass both tests; the node “7 in, 5 in” has total and is the first one pruned, by the test “too much already”.
Exercise 20.5 ★★
This generator forgets to swap back. Explain its output.
def permutations(a, k=0):
if k == len(a):
yield "".join(a)
return
for i in range(k, len(a)):
a[k], a[i] = a[i], a[k]
yield from permutations(a, k + 1)
['abc', 'acb', 'cab', 'cba', 'abc', 'acb'] 4 distinct
abc. Some lines are left out.Solution
Solution of Exercise 20.5.
Without the undo, the loop at position swaps with an array the recursive call has changed. After the first branch, the array is acb, not abc; the swap for brings c to the front instead of b, and after that branch the array is cba, so the swap for brings a back. The letter b never reaches the front: bac and bca are missing, abc and acb come twice. The number of outputs is still , so a test that only counts them misses the bug.
Exercise 20.6 ★★
The pruning “the partial sum is already above the target” is applied to values that can be negative. Explain the output, and give a sound test for this case.
without pruning: [[8, -2], [5, 3, -2]]
with pruning: []
Solution
Solution of Exercise 20.6.
Both solutions pass through a partial sum above 6 (8, and ) that a later negative value brings back: the pruning discards subtrees that hold solutions. A sound test uses the extreme sums still reachable: with the sum of the negative values among the undecided ones and that of the positive ones, prune when or . With positive values, and this is the chapter’s test.
Exercise 20.7 ★★
Write a generator of all the ways to write as a sum of distinct positive integers, with a pruning, and check the counts against another method.
Solution
Solution of Exercise 20.7.
def distinct_parts(n, largest=None):
"""The partitions of n into distinct parts <= largest, each list decreasing."""
if largest is None:
largest = n
if n == 0:
yield []
return
for part in range(min(n, largest), 0, -1):
if part * (part + 1) // 2 < n:
break # parts part, part-1, ..., 1 cannot reach n: prune
for rest in distinct_parts(n - part, part - 1):
yield [part] + rest
Parts are chosen in decreasing order, which makes each partition appear once. Parts at most part sum to at most ; when that is below , no smaller first part can do better, and the loop stops. The test compares the counts for with a dynamic-programming count (2 for , 10 for ).
Exercise 20.8 ★★
Write a word-search solver: is a word spelled in a grid of letters along a path of neighbouring cells (in eight directions), each cell used at most once?
Solution
Solution of Exercise 20.8.
def find(grid, word):
"""The path of cells (row, column) spelling word, or None."""
rows, cols = len(grid), len(grid[0])
path = []
def extend(r, c, k): # word[:k] is spelled by path, which ends next to (r, c)
if not (0 <= r < rows and 0 <= c < cols) or (r, c) in path:
return False
if grid[r][c] != word[k]:
return False
path.append((r, c))
if k + 1 == len(word):
return True
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if (dr or dc) and extend(r + dr, c + dc, k + 1):
return True
path.pop() # a dead end: free the cell
return False
for r in range(rows):
for c in range(cols):
if extend(r, c, 0):
return list(path)
return None
The partial solution is the path; a choice is a neighbour of its last cell; the constraints are the next letter and the unused cell. The removal of the cell after a dead end is the undo.
Exercise 20.9 ★★
Show that the tree of all partial orders of elements has nodes, and that this is less than .
Solution
Solution of Exercise 20.9.
The nodes at depth are the sequences of distinct elements, of them. Summing over and putting gives , which is less than . For : .
Exercise 20.10 ★★★
Colour the vertices of a graph with three colours so that no edge joins two vertices of the same colour, by backtracking, and test it against brute force. Compare with the encoding of colouring into a satisfiability problem of Chapter 10.
Solution
Solution of Exercise 20.10.
def colour(vertices, edges, k=3):
"""A dict vertex -> colour in range(k) with no edge inside one colour, or None."""
neighbours = {v: set() for v in vertices}
for a, b in edges:
neighbours[a].add(b)
neighbours[b].add(a)
order = sorted(vertices, key=lambda v: -len(neighbours[v])) # most neighbours first
colours = {}
def visit(i):
if i == len(order):
return True
v = order[i]
used = {colours[u] for u in neighbours[v] if u in colours}
for c in range(k):
if c not in used:
colours[v] = c
if visit(i + 1):
return True
del colours[v]
return False
return dict(colours) if visit(0) else None
The partial solution assigns colours to the first vertices of the order; a colour used by a coloured neighbour is never tried. The test compares with the assignments of 20 random graphs, and colours the town’s friendship graph (39 people, 50 friendships), which has no 2-colouring. The encoding of Chapter 10 turns the same question into clauses for a general solver: nothing in it is specific to graphs, which is its strength, and nothing uses the order of the vertices, which is the strength of the direct search.
Exercise 20.11 ★★★
Prove that the relaxation bound of the knapsack is at least the value of every completion of the partial solution, so that branch and bound still finds the optimum.
Solution
Solution of Exercise 20.11.
Let the remaining items be sorted by decreasing , with room . A completion chooses a set of them of weight at most ; with on and 0 elsewhere, it is a solution of the relaxed problem, so its value is at most the relaxed optimum. The greedy fill is that optimum: in any relaxed solution with room left over or with weight on an item of lower ratio while an item of higher ratio is not full, moving weight to the higher ratio does not lower the value; the greedy fill is the one where no such move is left. So the value of every completion, and a node with has no completion better than the best known: pruning it loses no improvement, and the optimum is still found.
Exercise 20.12 ★★★
For , the queens search visits 153 nodes. Using the left-right symmetry of the board, explain why it is for three subtree sizes, and find them by program.
Solution
Solution of Exercise 20.12.
The root has six children, the first queen in columns 0 to 5. The mirror maps the search below column onto the search below column , node for node, so the subtrees come in three equal pairs: . exercises/queens_subtrees.py gives , and .
20.7 Problem: Eight queens and their mirrors
Problem 20.1
Weekend problem — Eight queens and their mirrors
The eight queens problem has 92 solutions. Many are rotations or reflections of others. A program lists the solutions by brute force over the placements with distinct columns, applies to each the eight symmetries of the square, and groups them.
$ python queens_symmetry.py
92 solutions, 12 up to symmetry
orbit sizes: [4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8]
the symmetric one: (2, 4, 1, 7, 0, 6, 3, 5) unchanged by the half-turn: True
Part I — The encoding.
- Why must a solution have exactly one queen on each row and each column?
- Show that a solution is a permutation of with all distinct and all distinct.
- How many placements of 8 queens on 64 squares are there, and how many with one queen per row and column?
- What are the ranges of and , and how many diagonals of each direction are there?
- Why does a set of used diagonals make the attack test constant-time?
- Why does brute force over orders suffice here, though it would not for ?
Part II — Pruning.
- Read the nodes visited for with and without pruning, and their ratio.
- Why do the solutions of (4) number fewer than those of (10)?
- In what sense does the ratio of Output 20.3 grow?
- Placing queens column by column instead of row by row, would the counts change?
- Why is the first queen placed in all columns, while later queens have fewer candidates?
- Estimate the nodes for from the growth of the column.
Part III — Symmetries of the square.
- List the eight symmetries of the square (rotations and reflections) as maps of cells .
- Show that each maps a solution to a solution.
- The set of images of a solution is its orbit. Show that two orbits are equal or disjoint.
- Show that the size of an orbit is 8 divided by the number of symmetries that fix the solution.
- Show that no solution of eight queens is fixed by a reflection.
- Show that a solution fixed by the quarter-turn would have an orbit of at most 2 elements, and deduce from the output which symmetries fix the symmetric solution.
Part IV — Counting by program.
- What does the program check to call a permutation a solution?
- How does it compute an image under a symmetry, and why does it sort the moved cells?
- How are the orbits found, and why is each solution put in exactly one?
- Check .
- Check on the printed symmetric solution that the half-turn fixes it.
- State the named result, the eight-queens count: 92 solutions, 12 up to symmetry, eleven orbits of size 8 and one of size 4.
Solution
Solution of Problem 20.1.
1. Two queens on a row or a column attack each other, so each row holds at most one queen; eight queens on eight rows then hold exactly one each. The same for columns.
2. With the column of row ’s queen, distinct columns make a permutation. Two queens share a diagonal when or agree, so these values must all be distinct.
3. placements; with one queen per row and column.
4. runs from to 7, from 0 to 14: 15 diagonals in each direction.
5. The test asks whether a value is in a set, which is constant time on average for a hash set (Chapter 16): three such questions per candidate.
6. is about 40 thousand permutations, each tested in ; is about , far beyond what a Python loop goes through in reasonable time.
7. 2057 nodes with pruning, 109 601 without: 53 times fewer.
8. Nothing forces the counts to grow with : on the board the constraints happen to leave only 4 solutions, the images of a single one. The counts grow on the whole, but not at every step.
9. It roughly doubles with each (3.8, 6.0, 12.8, 24.8, 53.3, 117.5, 277.6): the gain itself grows exponentially, while both counts still grow exponentially.
10. No. Placing column by column on a board is placing row by row on the board turned about its diagonal, a square board with the same constraints: the tree is the same.
11. No queen is placed above the first row, so nothing attacks any of its cells; each later queen loses the columns and the diagonals of the queens above it.
12. The node count grows by a factor that rises from about 3 to 4.2; with factors near 4.5, the estimate for is about . (The program gives 856 189.)
13. With : the identity ; the quarter-turns and ; the half-turn ; the mirrors in the two axes and ; the mirrors in the two diagonals and .
14. Each is a bijection of the cells that maps rows and columns to rows or columns, and diagonals of either direction to diagonals. Two cells that share no line are mapped to two cells that share none: a solution goes to a solution.
15. The eight symmetries are closed under composition and inverse. If , then the images of are the , and runs over all eight symmetries: the orbit of is the orbit of . Two orbits that share an element are therefore both equal to that element’s orbit.
16. exactly when fixes . If symmetries fix , each image is reached by exactly symmetries, and the orbit has elements.
17. The mirror would need the queens of rows and in the same column. The mirror would need , impossible for an integer. Under , a queen off the main diagonal pairs with another at the mirror cell, and puts them on one diagonal; so all eight would sit on the main diagonal, which holds only one. The other diagonal mirror is the same with .
18. The quarter-turn generates four rotations; if it fixed , at least four symmetries would fix and the orbit would have at most 2 elements. The output has orbits of 8 and of 4 only. The orbit of 4 has a pair of symmetries fixing it, the identity and one of order 2: not a reflection (question 17), so the half-turn.
19. That the permutation has eight distinct values of and eight distinct values of .
20. It moves the eight cells, sorts them by row, and reads off the columns, so the image is written again as the list of the columns of rows 0 to 7, and equal solutions are equal tuples.
21. It takes the first solution not yet seen, computes the set of its images and marks them all as seen. By question 15 the orbits are disjoint, so each solution is in exactly one, found when its first member is met.
22. .
23. For , the half-turn needs : , , , , and the other four follow.
24. The eight-queens count: eight queens can be placed on a chessboard with no two attacking each other in 92 ways; up to the eight symmetries of the board there are 12, eleven with eight images and one, fixed by the half-turn, with four.