Pruning & Branch and Bound
Feasibility checks, bounds and ordering heuristics that shrink the search tree.
On this lesson's 20-item knapsack, the full search tree has 2,097,151 nodes, and checking only that items fit still leaves 1,241,198 to visit. Add one number per node, an optimistic bound on what its subtree could still achieve, and the same depth-first search visits 277. Branch and bound is the art of that number.
What you’ll learn
- Define feasibility pruning and bounding precisely, and prove that branch and bound returns an optimum whenever its bound is optimistic.
- Derive bounds from relaxations, the fractional bound for 0/1 knapsack and the Held–Karp 1-tree bound for the traveling salesman, and prove which nodes every branch-and-bound search must expand.
- Explain what fail-first ordering, propagation, symmetry breaking and iterative deepening each change about a search tree.
- Prove that Knuth's random-probe estimate of a tree's size is unbiased, and explain when its variance makes it unreliable.
Two reasons to cut a subtree
Fix an optimal solution , a leaf of . If no ancestor of is ever discarded, the search reaches , and the incumbent becomes at least as good:
Otherwise let be the first ancestor of to be discarded. Feasibility pruning never discards an ancestor of a feasible solution, so fell to bounding, and the incumbent at that moment satisfies
The incumbent is always feasible and only ever improves, so its final value is exactly the optimum. The children's order never entered the argument: ordering changes the work, not the answer.
Discarding on keeps one optimum; to list every optimum, discard only on . A good bound is valid (never below the truth), tight (close to it) and cheap (it is evaluated at every node). The standard source is a relaxation: drop a hard constraint and solve the easier problem exactly. Its optimum can only be at least as good as the original's, so it is a valid bound by construction.
Bounds from relaxations
In the 0/1 knapsack problem, item has value and weight , and a set of items of total weight at most must maximize the total value. Relax to (an LP relaxation) and you get the fractional knapsack, which greedy solves exactly (Dantzig, 1957): sort the items by value per unit weight, fill, and take a fraction of the first item that does not fit.
Number the items so that , where . If a fractional solution has and for some , moving weight from item to item keeps the total weight and changes the value by
Repeated exchanges turn any optimal fractional solution into the greedy fill without lowering its value, so the greedy fill is optimal for the relaxation. At a node that has decided items , with value collected and room left, define
Every 0/1 completion of is also a fractional one, so is optimistic. On this lesson's instance the root bound is about 390.9 and the optimum is 386, a gap near 1%, which is why the bound cuts so much.
def knapsack_bb(items, cap, use_bound=True):
"""items: (value, weight) pairs. Depth-first branch and bound; returns (best, nodes)."""
items = sorted(items, key=lambda vw: vw[0] / vw[1], reverse=True) # best ratio first
best = nodes = 0
def bound(i, value, room): # optimum of the fractional relaxation of items[i:]
for v, w in items[i:]:
if w > room:
return value + v * room / w # a fraction of the first item that does not fit
value, room = value + v, room - w
return value
def go(i, value, room):
nonlocal best, nodes
nodes += 1
best = max(best, value) # every node is a feasible packing: an incumbent
if i == len(items) or (use_bound and bound(i, value, room) <= best):
return # a leaf, or no completion can beat the incumbent
v, w = items[i]
if w <= room: # feasibility: take item i only if it fits
go(i + 1, value + v, room - w)
go(i + 1, value, room) # leave item i out
go(0, 0, cap)
return best, nodes
weights = [12 + 37 * i % 41 for i in range(20)]
items = [(w + 7 * i % 11, w) for i, w in enumerate(weights)] # values track weights: a hard type
print(knapsack_bb(items, sum(weights) // 2, use_bound=False)) # (386, 1241198)
print(knapsack_bb(items, sum(weights) // 2)) # (386, 277)Each value is its weight plus at most 10, the "strongly correlated" kind of instance on which simple bounds struggle most; the capacity is 314. The optimum, 386, was checked against all subsets.
| Search on the 20-item instance | Nodes |
|---|---|
| The whole tree, every subset | |
| Feasibility pruning only | 1,241,198 |
| Feasibility and the fractional bound, depth first | 277 |
| The same bound, best first (a priority queue of open nodes by bound) | 194 expanded |
So best-first is optimally efficient for a given bound, up to ties at , just as A* is for a given heuristic. Its price is memory: the open list can grow exponentially, while depth-first search stores a single path. Practical solvers mix the two, diving depth first for a good incumbent early and then working on the best bounds.
For the symmetric traveling salesman problem on vertices , a 1-tree is a spanning tree of vertices plus two edges at vertex 1. Delete vertex 1's two edges from any tour and a Hamiltonian path on the other vertices remains, which is a spanning tree; so every tour is a 1-tree, and the cheapest 1-tree, one MST computation plus two edges, is a lower bound on the optimal tour.
Add a penalty to every edge at vertex . A tour has degree exactly 2 at every vertex, so every tour's cost shifts by the same constant, and the optimal tour does not change:
The cheapest 1-tree does change with , so every choice of penalties gives a lower bound:
Raise where the current 1-tree has degree above 2, lower it where the degree is 1, and repeat (a subgradient ascent). The limit is the Held–Karp bound, which equals the optimum of the subtour-elimination linear program and is usually very close to the optimal tour on geometric instances. If some makes the cheapest 1-tree a tour, that tour is optimal.
Order, propagate, break symmetry
A bound decides whether a subtree is worth visiting; the branching order decides what the tree looks like. In a constraint problem the search chooses, at each node, which variable to assign next. The fail-first principle (Haralick & Elliott, 1980) picks the variable with the fewest values left, the heuristic known as minimum remaining values (MRV). Small branching near the root keeps the tree narrow, and a variable whose values have all run out is noticed at once rather than many levels later.
Three more tools reshape the tree:
- Value order. Try the most promising value first. When a search lists all solutions, or proves there are none, value order only permutes siblings, so the tree is the same size. In branch and bound it matters a great deal, because a good incumbent found early tightens every later bound.
- Symmetry breaking. The 8 symmetries of a chessboard map n-queens solutions to solutions. Restricting the first queen to the left half of its row and counting each solution twice (its mirror image) halves the 8-queens search, from 2,057 nodes to 1,029, with 46 solutions doubled to 92; for odd the middle column needs separate care. In general, add constraints that keep one representative per symmetry class, such as lexicographic order.
- Remembering failures. When a dead end is caused by only some of the current choices, record that combination (a nogood) and never try it again. SAT solvers do this systematically by learning clauses (CDCL; see SAT Solvers in Practice).
Iterative deepening (Korf, 1985) runs depth-limited DFS with limits until a solution appears. Memory stays linear in the depth, and the repeated shallow work is cheap because most of a tree's nodes sit in its deepest level:
A backtracking search lists all solutions of a constraint problem, with no bounding. Which change can never reduce the number of nodes it visits?
- Choosing the variable with the fewest remaining values first
- Forward checking
- Trying each variable's values in a smarter order
- Breaking the problem's symmetries
Show the answer
C. Trying each variable's values in a smarter order
To list everything, the search must enter every child of every node it visits. Value order only changes the order of siblings, so the set of visited nodes is the same. It pays off only when the search can stop early: at the first solution, or in branch and bound, where an early incumbent prunes later subtrees.
How big is the tree? Knuth’s estimator
Before you commit hours to a search, estimate its size. Knuth (1975) proposed a one-line experiment: walk from the root to a leaf, choosing a child uniformly at random at every node, and record the numbers of children seen along the way. Then estimate
Write for the estimate of a probe started at . A leaf gives . If has children, the probe moves to a uniformly random child and continues from there, so
Average over the equally likely children and use the induction hypothesis :
import random
def probe(n):
"""One random root-to-leaf walk in the n-queens tree; returns Knuth's estimate of its size."""
queens, estimate, width = [], 1, 1 # width: the estimated size of the next level
while True:
r = len(queens)
free = [c for c in range(n)
if all(c != qc and abs(c - qc) != r - qr for qr, qc in enumerate(queens))]
if not free:
return estimate # a leaf: a solution or a dead end
width *= len(free)
estimate += width
queens.append(random.choice(free))
samples = [probe(8) for _ in range(100_000)]
print(sum(samples) / len(samples)) # close to 2057, the true number of nodesTwo runs of 100,000 probes averaged 2,061.8 and 2,060.6. The pruned 8-queens tree has 2,057 nodes.
Unbiased is not the same as reliable. For 8 queens the exact distribution of has mean 2,057 but standard deviation about 1,071: single probes range from 489 to 7,409, and 82% of them fall within a factor of 2 of the truth. Averaging probes divides the standard deviation by . On lopsided trees, where most nodes hide below a few rarely chosen branches, the variance can be astronomically larger; Purdom (1978) and Chen (1992) reduced it by exploring several children per node or by stratifying the sample. Knuth also noted that branch and bound does not fit the model directly, because its tree depends on an incumbent that a single probe cannot know.
A probe sees 3 children at the root, then 2, then 2, and then reaches a leaf. What is its estimate ?
Show the answer
22
: the root, then the estimated sizes of levels 1, 2 and 3. A tree with these branching factors at every node would have exactly 22 nodes.
Key takeaways
- Feasibility pruning discards subtrees that hold no solution; bounding discards subtrees whose optimistic bound cannot beat the incumbent. With an optimistic bound, branch and bound always returns an optimum, in any exploration order.
- Good bounds come from relaxations: the greedy fractional fill for 0/1 knapsack (277 nodes instead of 1,241,198 on this lesson's instance) and Held and Karp's penalized 1-trees for the traveling salesman.
- Every branch and bound must expand the nodes with bound above the optimum; best-first expands nothing below it but may need exponential memory, while depth-first keeps one path and finds incumbents early.
- Fail-first variable order, propagation and symmetry breaking reshape the tree, while value order matters only when the search can stop early; Knuth's estimate predicts a tree's size without bias, exactly on uniform trees and noisily on lopsided ones.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A branch-and-bound search for a maximum uses a "bound" that sometimes falls below the best value actually present in a subtree. What can happen?
- Nothing: the incumbent protects the answer
- The search gets slower but stays correct
- It may discard the subtree that holds the optimum and return a worse solution
- It may never terminate
Show the answer
C. It may discard the subtree that holds the optimum and return a worse solution
The exactness proof needs for every solution below . If underestimates, a subtree containing the optimum can be discarded while the incumbent is still worse than the optimum, and nothing ever revisits it.
Compared with depth-first branch and bound using the same monotone bound, best-first branch and bound...
- uses less memory, because it stores only the open nodes
- never expands a node whose bound is below the optimum, but may hold exponentially many open nodes
- can return a better solution
- does not need an incumbent
Show the answer
B. never expands a node whose bound is below the optimum, but may hold exponentially many open nodes
Best-first expands nodes in decreasing order of bound and stops once the best open bound is at most the incumbent, so a node with is never expanded. The open list, however, can grow exponentially, whereas depth-first search keeps one root-to-leaf path.
For which trees does a single Knuth probe always return the exact number of nodes?
- Binary trees
- Trees whose leaves all lie at the same depth
- No tree: the estimate is a random variable
- Trees in which all nodes at the same depth have the same number of children
Show the answer
D. Trees in which all nodes at the same depth have the same number of children
Then every root-to-leaf walk sees the same , so every probe returns , which is exactly the number of nodes: the estimator has zero variance. The permutation tree is an example: on 4 items every probe returns .
Iterative deepening runs on a uniform tree with branching factor 3. All its iterations together visit about how many times the nodes of the final depth-limited search?
- 3
- 1.5
- 2
- , the final depth
Show the answer
B. 1.5
Level holds nodes, so the earlier iterations add a geometric fraction of the last one: the total is about times the final iteration. Most of a tree's nodes sit in its deepest level.
Further reading
- A. H. Land & A. G. Doig, "An automatic method of solving discrete programming problems," Econometrica 28(3) (1960), 497–520.
- M. Held & R. M. Karp, "The traveling-salesman problem and minimum spanning trees," Operations Research 18(6) (1970), 1138–1162; Part II, Mathematical Programming 1 (1971), 6–25.
- D. E. Knuth, "Estimating the efficiency of backtrack programs," Mathematics of Computation 29 (1975).
- R. M. Haralick & G. L. Elliott, "Increasing tree search efficiency for constraint satisfaction problems," Artificial Intelligence 14 (1980), 263–313.
- D. L. Applegate, R. E. Bixby, V. Chvátal & W. J. Cook, The Traveling Salesman Problem: A Computational Study (Princeton University Press, 2006).