Skip to main content

Branch and Bound: Classic Problems

This lesson applies the general scheme of branch and bound to several problems. In each one, the work consists of answering the same three questions:

  1. What is a state, and what are its children?
  2. What is the heuristic (the lower bound, for minimization) that orders the live nodes and decides what to prune?
  3. What is the initial pruning limit?
What you will learn in this lesson
  • How to define states, optimistic bounds, and initial limits for six classic problems: task assignment, 0/1 knapsack, sliding puzzles, rectangle placement, N-queens, and the traveling salesman.
  • Why a tight bound (such as the fractional greedy bound for 0/1 knapsack) can cut the number of expanded nodes by orders of magnitude.
  • How admissible heuristics (g+hg + h, Manhattan distance) and parity reachability apply to the 8/15-puzzle.
  • How to mirror minimization bounds into upper bounds for maximization problems.
ProblemTypeHeuristicWhat it illustrates
Task assignmentMinimizationCost so far + cheapest remaining cost of each columnA complete trace; initial limit
0/1 knapsackMaximizationValue so far + fractional (greedy) completionMirrored bounds; the power of a tight bound
Sliding puzzlesMinimum number of movesMoves made + Manhattan distanceReachability test; repeated states; g+hg + h
Rectangle placementMinimizationArea of the bounding box so farGeometric states
N-queensFirst solutionQueens left to place, then diagonal lengthB&B used to find one solution fast
Traveling salesmanMinimizationLength so far + cheapest exit of each city still to leaveA bound for a classic NP-hard problem

Task assignment​

Problem. There are nn agents and nn tasks. Each agent performs exactly one task and each task is performed by exactly one agent. The cost of agent ii performing task jj is C[i][j]C[i][j]. Find the assignment with minimum total cost. (This problem was solved by backtracking in the previous lesson; now we solve it with branch and bound.)

We use this cost matrix, with agents a,b,c,da, b, c, d and tasks 1 to 4:

Agent \ Task1234
a11121840
b14151322
c11171923
d17142028

Design​

  • State: the tasks assigned to the first kk agents. Level kk decides the task of agent k+1k + 1, so each node has one child per task still free. When only one agent is left, its task is forced, so the last two agents are decided together.
  • Heuristic (lower bound): the sum of the costs already assigned, plus, for each task still free, the minimum cost in its column among the agents still free. Each remaining task will be done by someone, and at best by its cheapest remaining agent, so this never overestimates. (It may be too optimistic: the same agent could be the cheapest for two tasks.)
  • Initial pruning limit: the cheaper of the two diagonals of the matrix. Each diagonal is a valid assignment (agent ii gets task ii, or task n+1−in + 1 - i), so the optimum cannot be worse:
U0=min⁡(11+15+19+28,  40+13+17+17)=min⁡(73,87)=73U_0 = \min(11 + 15 + 19 + 28,\; 40 + 13 + 17 + 17) = \min(73, 87) = 73

For example, the state "a gets task 1" has heuristic 1111 (assigned) +min⁡(15,17,14)+ \min(15, 17, 14) (column 2) +min⁡(13,19,20)+ \min(13, 19, 20) (column 3) +min⁡(22,23,28)+ \min(22, 23, 28) (column 4) =11+14+13+22=60= 11 + 14 + 13 + 22 = 60.

Trace​

The live nodes are kept in a priority queue ordered by heuristic. The search proceeds as follows (the limit is shown after each step):

StepNode expandedChildren generated (heuristic)Limit
1roota1 (60), a2 (58), a3 (65), a4 (78, pruned: 78 ≥ 73)73
2a2 (58)b1 (68), b3 (59), b4 (64)73
3a2 b3 (59)c1 d4: solution, cost 64; c4 d1: solution, cost 6564
4a1 (60)b2 (68, pruned), b3 (61), b4 (66, pruned)64
5a1 b3 (61)c2 d4: solution, cost 69; c4 d2: solution, cost 6161
6The best live node is a2 b4 (64) ≥ 61: stop61
Branch and bound for the task assignment example: expanded nodes, pruned nodes and solutionsroot1a1: 604a2: 582a3: 65a4: 78b2: 68b3: 615b4: 66b1: 68b3: 593b4: 64c2 d4: 69c4 d2: 61c1 d4: 64c4 d1: 65pruned: 78 ≥ 73optimum: 61first solution: 64orange number: order of expansion · red: pruned when generated · gray: still alive when the search stops (64, 65 and 68 ≥ 61) · green: optimum
The search tree of the trace. The orange numbers give the order of expansion; nodes whose bound reaches the limit are pruned (red) as soon as they are generated, and the search stops when no live node (gray) can beat the solution of cost 61.

The optimal solution is (a, 1), (b, 3), (c, 4), (d, 2), with cost 11+13+23+14=6111 + 13 + 23 + 14 = 61.

Only 4 complete assignments were generated (6 if we count the two diagonals used for the initial limit), instead of the 4!=244! = 24 that exhaustive backtracking examines. Nodes a3, a4, a2 b1, a1 b2 and a1 b4 were never expanded.

At scale​

On random n×nn \times n matrices with costs between 1 and 99, we compared this B&B with the backtracking algorithm of the previous chapter (which prunes only when the cost so far reaches the best cost):

nnBacktracking: recursive callsB&B: nodes expandedB&B: nodes generated
1012,7392181,420
1277,41269565
14194,17941332

Both return the same optimum. The difference comes from the estimate of the future cost: backtracking only knows what has already been spent, while the B&B bound also accounts for what must still be spent, so it detects hopeless branches much earlier. For a walkthrough of the same technique, see Assignment Problem using Branch and Bound.

ProofThe bounds used in the examples are valid

0/1 knapsack​

Problem. We have nn objects with weights wiw_i and values viv_i, and a knapsack with capacity WW. Choose objects (each one entirely or not at all) to maximize the total value without exceeding the capacity. We solved it with dynamic programming in pseudo-polynomial time; branch and bound solves it without depending on the size of WW.

Design​

  • State: decisions taken for the first kk objects (take it or leave it), with the weight and value accumulated. Each node has at most two children.
  • This is a maximization problem, so everything is mirrored: the bound is an optimistic upper bound on the value reachable from the node, the benchmark is the best value found so far, and a node is pruned when its bound is less than or equal to that value.
  • Bound: sort the objects by value per unit of weight vi/wiv_i / w_i, decreasing. From the current state, keep adding the remaining objects in that order while they fit, and fill the remaining capacity with a fraction of the next one. This is the greedy solution of the fractional knapsack, which is optimal for the relaxed problem, so it can never be worse than the true best completion.

Example​

Use the instance from the dynamic programming lesson: W=10W = 10, and three objects with weights 6,5,56, 5, 5 and values 8,5,58, 5, 5 (ratios 1.331.33, 11, 11, already sorted).

  • Root: take object 1 (weight 6, value 8), 4 units of capacity left, take 4/54/5 of object 2 (value 4): bound =12= 12.
  • Expand the root:
    • "take 1": value 8, bound 8+4=128 + 4 = 12. The best value so far becomes 8.
    • "leave 1": objects 2 and 3 fit: bound =10= 10.
  • Expand "take 1" (12). Object 2 does not fit. Leaving it gives bound 8+45⋅5=128 + \tfrac{4}{5} \cdot 5 = 12; expanding that, object 3 does not fit either, and the complete solution has value 8.
  • Expand "leave 1" (its bound, 10, is greater than 8). "Take 2": value 5, bound 10. "Leave 2": bound 5 ≤ 8, pruned.
  • Expand "take 2" (10). "Take 3": value 10, which becomes the best value. "Leave 3": bound 5, pruned.
  • No live node can beat 10: stop. The optimum is objects 2 and 3, value 10.
Best-first branch and bound for the knapsack example: bounds, pruned nodes and the optimum 10root: b 121take 1: v 8, b 122leave 1: b 104leave 2: b 123leave 3: v 8take 2: v 5, b 105leave 2: b 5take 3: v 10leave 3: b 5object 2 does not fitobject 3 does not fit5 ≤ best: prunedv: value so far · b: optimistic bound (fractional knapsack) · orange: order of expansion · green: optimum
The search for the knapsack example. Each node shows the value carried so far (v) and its optimistic bound (b); the branch with the best bound, take 1, is explored first but only reaches 8, and the optimum, 10, is in the other branch.

The example also shows that the first branch explored (the one with the most attractive bound) does not always contain the optimum: the fractional bound of "take 1" was 12, but its true best completion is only 8. The bound was optimistic, as required, and the search corrected itself.

🧠 Checkpoint: Compute the bound

Question: A knapsack with capacity W=8W = 8 and three objects with weights 4, 5, 3 and values 12, 10, 3 (ratios 3, 2, 1, already sorted). What is the bound of the root? What is the optimum?

Answer: Root: take object 1 (weight 4, value 12), 4 units left, and 4/54/5 of object 2 (value 8): bound 20. The optimum is objects 1 and 3 (weight 7), value 15; objects 1 and 2 do not fit together. The bound is optimistic, as it must be.

The power of a tight bound​

On 30 random objects (weights between 10 and 99, capacity half of the total weight):

AlgorithmNodes or callsTime
Backtracking, pruning only objects that do not fitabout 1,207 million calls2.3 s
Backtracking + fractional bound251 calls0.2 ms
Best-first B&B + fractional bound122 nodes expanded1.6 ms

All three return the same value. The bound is responsible for almost all of the improvement; the best-first order then halves the number of nodes, at the price of creating node objects and managing a priority queue. On instances with 40 and 50 objects, the bounded versions still need only a few hundred nodes.

ProofThe bounds used in the examples are valid

Sliding puzzles​

Problem. The 15-puzzle is played on a 4×44 \times 4 board with 15 numbered tiles and one empty cell. A move slides a tile adjacent to the empty cell into it (equivalently, the empty cell moves to one of its up to four neighbors). Pieces cannot be lifted. Starting from a scrambled board, reach the goal state with the tiles in order and the empty cell in the last position, using as few moves as possible. The 8-puzzle is the same game on a 3×33 \times 3 board.

The 15-puzzle: an initial state and the goal state142312948131011751156initial state123456789101112131415goal statefewest moves?
An initial state of the 15-puzzle and the goal state. A move slides a tile into the empty cell.

The state space​

The board can be in 16!≈2.1×101316! \approx 2.1 \times 10^{13} configurations. Only half of them can be reached from a given initial state, but that is still about 101310^{13} states: building and exploring the whole tree is unacceptable. Before searching, we should know whether the goal is reachable at all.

Reachability test​

Number the cells from 1 to 16, row by row, and treat the empty cell as tile 16. Define:

  • position(i)\text{position}(i): the cell where tile ii is in the initial state;
  • smaller(i)\text{smaller}(i): the number of tiles j<ij \lt i such that position(j)>position(i)\text{position}(j) \gt \text{position}(i) (smaller tiles that appear after tile ii);
  • x=1x = 1 if the empty cell is in one of the shaded cells of a checkerboard pattern (cells 2, 4, 5, 7, 10, 12, 13 and 15), and x=0x = 0 otherwise.

Then the goal state is reachable if and only if

∑i=116smaller(i)+x is even.\sum_{i=1}^{16} \text{smaller}(i) + x \text{ is even.}

The reason is a parity argument: every move changes the parity of the number of inversions (horizontal moves by exactly one inversion, vertical moves by an odd number) and also changes the color of the square where the empty cell is, so the parity of the total never changes. The goal has sum 0 and x=0x = 0.

Example 1. For the board

Example 1 of the reachability test of the 15-puzzle: the empty cell is in cell 6, which is not shaded, and the sum is 37, odd, so the goal is unreachable134152512761114891013sum 37 + x 0 = 37, oddunreachable
Example 1. The purple cells are the shaded cells of the checkerboard pattern; the empty cell, 6, is not one of them.

the values are smaller(3)=smaller(4)=smaller(7)=1\text{smaller}(3) = \text{smaller}(4) = \text{smaller}(7) = 1, smaller(11)=3\text{smaller}(11) = 3, smaller(12)=6\text{smaller}(12) = 6, smaller(14)=4\text{smaller}(14) = 4, smaller(15)=11\text{smaller}(15) = 11 and smaller(16)=10\text{smaller}(16) = 10, all the others 0. The sum is 37, and the empty cell is in cell 6, which is not shaded (x=0x = 0). The total, 37, is odd: the goal cannot be reached, and the search should not even start.

Example 2. For the board

Example 2 of the reachability test of the 15-puzzle: the empty cell is in cell 11, which is not shaded, and the sum is 8, even, so the goal is reachable123456789101113141512sum 8 + x 0 = 8, evenreachable
Example 2. The empty cell, 11, is not shaded, and the sum is even.

smaller(13)=smaller(14)=smaller(15)=1\text{smaller}(13) = \text{smaller}(14) = \text{smaller}(15) = 1 and smaller(16)=5\text{smaller}(16) = 5, so the sum is 8, with x=0x = 0 (cell 11 is not shaded). The total is even: the goal is reachable (in fact, with 2 moves). The initial state shown at the beginning of this section is also reachable (sum 64, x=0x = 0).

For the 8-puzzle (odd board width), the rule is simpler: the goal is reachable if and only if the number of inversions among the 8 tiles, ignoring the empty cell, is even.

ProofThe parity condition of the 15-puzzle
🧠 Checkpoint: Reachable or not?

Question: Is the goal reachable from the 8-puzzle board 1 2 3 / 4 5 6 / 8 7 _ (the empty cell last)?

Answer: No. Ignoring the empty cell, the tiles read 1 2 3 4 5 6 8 7, with a single inversion (8 before 7). The number is odd, so the goal is unreachable: no search is needed to know it.

Heuristics​

Two classic estimates of how far a board is from the goal:

  • Misplaced tiles: the number of tiles that are not in their final cell.
  • Manhattan distance: the sum, over all tiles, of the number of rows plus columns that separate each tile from its final cell.

Both are admissible: each misplaced tile needs at least one move, and each move changes the Manhattan distance of only one tile by one. The empty cell must not be counted, or the estimate may exceed the true number of moves. Manhattan distance is always at least as large as the number of misplaced tiles, so it is the tighter (better) of the two.

Two admissible heuristics for an 8-puzzle board: misplaced tiles and Manhattan distance28316475board12345678goal121122misplaced tiles: 6(blue tiles: 1, 2, 4, 5, 6, 8)Manhattan distance: 9(orange: rows + columns to its cell)both ≤ the true number of moves
An 8-puzzle board and the goal. Six tiles are misplaced (blue); the orange numbers are the Manhattan distance of each tile to its cell, 9 in total. Both estimates are lower than or equal to the real number of moves.
ProofThe puzzle heuristics are admissible

Ordering the live nodes: g+hg + h​

To find the solution with the fewest moves, the priority of a board xx must be

f(x)=g(x)+h(x)f(x) = g(x) + h(x)

where g(x)g(x) is the number of moves already made from the initial state and h(x)h(x) an admissible heuristic. This is the A* algorithm described in the previous lesson. The B&B must also discard repeated states: otherwise it would keep generating boards it has already seen, moving tiles back and forth.

We solved 200 random solvable 8-puzzles with four strategies:

StrategyAverage moves in the solutionAverage boards expanded
Breadth-first (FIFO queue)22.3 (optimal)83,701
Best-first, gg + misplaced tiles22.3 (optimal)15,682
Best-first, gg + Manhattan distance22.3 (optimal)1,266
Best-first, Manhattan distance only (no gg)64.7292

The three strategies that include gg always find the shortest solution, and the better the heuristic, the fewer boards they expand. The last one expands fewer boards still, but its solutions are almost three times longer than necessary: in 194 of the 200 puzzles it returned a non-optimal solution, in one case with 142 extra moves. Forgetting gg turns branch and bound into a greedy search.


Rectangle placement​

Problem. We have nn flat rectangular pieces p1,…,pnp_1, \dots, p_n, where piece pip_i measures ai×bia_i \times b_i. We want to place them on a flat board, without overlapping, so that the area of the rectangle that encloses all of them is minimum. A real application is arranging boxes in a warehouse with robotic arms, or cutting pieces from a sheet of material with minimum waste.

For example, with p1=1×2p_1 = 1 \times 2, p2=2×2p_2 = 2 \times 2 and p3=1×3p_3 = 1 \times 3, different arrangements need enclosing boxes of 4×3=124 \times 3 = 12, 7×2=147 \times 2 = 14, 5×2=105 \times 2 = 10 or 3×3=93 \times 3 = 9. The last one is optimal: the pieces have a total area of 2+4+3=92 + 4 + 3 = 9, so they fill the 3×33 \times 3 square without gaps (the 2×22 \times 2 piece in a corner, the 1×21 \times 2 piece standing next to it, and the 1×31 \times 3 piece along the remaining side).

Design​

  • State: a matrix of integers representing the board, where 0 marks a free cell and a value k>0k \gt 0 marks a cell occupied by piece pkp_k. At step kk the next piece not yet placed is added.
  • Children: one child for each valid position of the next piece, both horizontal and vertical. A position is valid if it does not overlap the pieces already placed and is adjacent to at least one of them (placing a piece far away can only make the box bigger).
  • Solution: a node at level nn (all pieces placed). The problem always has a solution if the board is large enough.
  • Bound: the area of the enclosing box of the pieces placed so far can only grow when more pieces are added, so it is a valid lower bound. A node is pruned when that area already reaches the area of the best solution found.

A stronger bound uses the fact that the final box must also contain the area of the pieces not yet placed: max⁡(current box area,total area of all pieces)\max(\text{current box area}, \text{total area of all pieces}).


N-queens​

Branch and bound is not only for optimization. Here it is used to find one placement of nn non-attacking queens (the problem solved by backtracking) as fast as possible. Only states in which no queen attacks another are generated.

Branching heuristic​

  1. Develop first the state with more queens placed: it is closer to a solution.
  2. In case of a tie, prefer the state whose last queen is on a cell whose longest diagonal is the shortest. A queen on a short diagonal attacks fewer cells, so it leaves more room for the remaining queens.

Let diagonal(i,j)\text{diagonal}(i, j) be the length of the longest diagonal passing through cell (i,j)(i, j). For a 5×55 \times 5 board:

54345
45454
34543
45454
54345

To merge both criteria into one number (lower is better), the first criterion is multiplied by 10 so that it always dominates the second:

h=(n−queens placed)⋅10+diagonal(i,j)h = (n - \text{queens placed}) \cdot 10 + \text{diagonal}(i, j)

For n=5n = 5, the five children of the root (one queen in the first column) get the values 45, 44, 43, 44 and 45, so the search starts with the queen in the middle row of the first column, on the short diagonal.

Effect​

We counted the states expanded to find the first solution, compared with the recursive calls of first-solution backtracking:

nnBacktracking (calls)B&B (states expanded)
811431
1610,05317
20199,63659
24411,609253
283,006,29992,956

The heuristic guides the search towards a solution far more directly. It is not perfect (for n=28n = 28 it needs many more states than for n=24n = 24), which is a reminder that heuristics improve typical behavior, not the worst case.


The traveling salesman​

Problem. A salesman must visit nn cities, each exactly once, and return to the city where he started. The distance d(i,j)d(i, j) between every pair of cities is known. Find the shortest tour. It is the most famous NP-hard problem, and branch and bound is the basis of the exact methods used to solve it.

Design​

  • State: a partial tour that starts at city A, with the cities visited so far in order, and its length. Each child adds one unvisited city at the end.
  • Solution: a state that has visited all nn cities; its cost includes the return to A.
  • Lower bound: in the final tour, every city that has not been left yet will have to be left exactly once. So a valid bound is the length so far, plus the cheapest edge from the current city to an unvisited city, plus, for each unvisited city, its cheapest edge to another unvisited city or back to A. Each term is a minimum over the edges that the tour could still use, so the sum never exceeds the length of any completion.

An example​

Five cities, A to E, with these symmetric distances:

ABCDE
A1210198
B12372
C103620
D19764
E82204

At the root nothing has been decided, and every city must still be left once: the bound is the sum of the smallest distance of each row, 8+2+3+4+2=198 + 2 + 3 + 4 + 2 = 19. The best-first search expanded 13 nodes and generated 31, and found the optimal tour A → C → B → D → E → A, of length 10+3+7+4+8=3210 + 3 + 7 + 4 + 8 = 32. There are only 24 tours starting at A here, so the saving is modest; it grows quickly with nn.

At scale​

On random instances with symmetric distances between 10 and 99, we compared this branch and bound with a backtracking search that prunes only when the length so far reaches the best tour found:

CitiesBacktracking: callsB&B: nodes expandedB&B: nodes generated
10115,1734542,118
121,187,7586444,129
1312,072,1244,23026,759

Both find the same optimum. As in the assignment problem, the difference comes from the bound, which accounts for the length still to travel. Real solvers such as Concorde use much stronger bounds (based on spanning trees and linear programming) and solve instances with tens of thousands of cities.

Common mistakes
  • Bounding the 0/1 knapsack with an integer greedy completion. It is not an upper bound; use the fractional one.
  • Searching a sliding puzzle that has no solution. Check first whether the configuration is reachable.
  • Ordering the priority queue in the wrong direction. Minimize costs, maximize values: the most promising node must come out first.

Summary​

ProblemStateHeuristic / boundInitial limit
Task assignmentTasks of the first kk agentsCost so far + minimum of each free columnCheaper diagonal
0/1 knapsackDecisions on the first kk objectsValue so far + fractional greedy completion (upper bound)Value of the greedy solution, or 0
Sliding puzzlesBoard configurationgg (moves made) + Manhattan distanceInfinite (stop at the first goal extracted)
Rectangle placementBoard matrix with the pieces placedArea of the enclosing box so farInfinite, or any valid arrangement
N-queensQueens placed so far, without attacks(n−placed)⋅10+diagonal(n - \text{placed}) \cdot 10 + \text{diagonal}Not needed (first solution)
Traveling salesmanPartial tour from ALength so far + cheapest exit of the current and of each unvisited cityInfinite, or the length of a greedy tour

Practice​

  • ⚖️ Loose vs. tight bound. On a 0/1 knapsack instance with 20 items, compare the number of nodes expanded using the fractional greedy upper bound versus the trivial bound (value so far + sum of all remaining values).
  • 🧮 Initial limit. In the task assignment problem (n=12n = 12), compare starting with an infinite initial limit versus starting with the cost of the main diagonal or a greedy assignment.
  • 🧩 Reachability first. Given two 8-puzzle start states (one solvable and one with two tiles swapped), verify their inversion parity before running A* and observe what happens if the check is skipped.
  • 🗺️ TSP at scale. Measure how many nodes branch and bound expands on random symmetric TSP instances for n=8,10,12n = 8, 10, 12 and note both execution time and peak heap size.
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.