Skip to main content

The Branch and Bound Scheme

15 min readRead first: The Backtracking Scheme · Data Structures

Branch and bound (B&B) is the last design technique of the course. Like backtracking, it searches an implicit tree of states: nodes represent states of the problem, edges represent valid changes, and solving the problem means finding a node (or a path) in that tree. The difference is the order in which the tree is explored, and that single change makes it suitable for different problems.

  • Backtracking goes deep first: it follows one branch to the end before trying another.
  • Branch and bound generates all the children of a node before moving on, keeps the generated nodes in a data structure, and always continues from the most promising one. It adds bounds (optimistic estimates) to discard whole subtrees that cannot contain the solution we are looking for.

The name describes the two ingredients: branch (generate the children of a node, in an order chosen by a heuristic) and bound (estimate how good the best solution below a node can be, and prune the node if that estimate is not good enough).

What you will learn in this lesson
  • How breadth-first and best-first exploration differ from depth-first backtracking.
  • The role of the priority queue of live nodes and the branching heuristic.
  • What makes a valid bound (optimistic, cheap, and tight) and how the initial pruning limit accelerates search.
  • How A* arises as a special case of best-first branch and bound with f(n)=g(n)+h(n)f(n) = g(n) + h(n).
  • When to choose branch and bound over backtracking, and the memory trade-offs involved.

Four ways to explore the same tree​

Consider this tree, where the number next to each node is an estimate of how good the solutions below it are (lower is better):

The same tree explored in four orders; the numbers give the order of expansiondepth-first (stack)A(10)1B(14)2C(11)5D(12)7E(15)3F(16)4G(13)6H(11)8I(12)9A B E F C G D H Idepth-first, best child firstA(10)1B(14)7C(11)2D(12)4E(15)8F(16)9G(13)3H(11)5I(12)6A C G D H I B E Fbreadth-first (queue)A(10)1B(14)2C(11)3D(12)4E(15)5F(16)6G(13)7H(11)8I(12)9A B C D E F G H Ibest-first (priority queue)A(10)1B(14)7C(11)2D(12)3E(15)8F(16)9G(13)6H(11)4I(12)5A C D H I G B E F
The four strategies on the same tree; the small numbers give the order in which the nodes are expanded. Only best-first jumps between branches, guided by the estimates, and leaves branch B for last.

The four classic strategies visit the nodes in different orders:

StrategyData structureOrder of expansion
Depth-first (plain backtracking)Recursion stack (LIFO)A B E F C G D H I
Depth-first with domain knowledge (backtracking that tries the best child first)Recursion stackA C G D H I B E F
Breadth-first (B&B without heuristic)Queue (FIFO)A B C D E F G H I
Best-first (B&B with a branching heuristic)Priority queueA C D H I G B E F

The first two strategies are backtracking: once they enter a branch, they cannot leave it until every node in it has been visited. Ordering the children helps, but only locally. The last two are branch and bound: the nodes generated so far wait in a data structure, and the next node to expand can come from any level and any branch of the tree.

In best-first order, after expanding A the algorithm expands C (11), then D (12), which is cheaper than G (13), then H (11) and I (12), and only then goes back to G. Branch B (14) is left for last, and if a solution of cost 13 or less has been found by then, B is never expanded at all.


Breadth-first search: advantages and costs​

Exploring level by level has an important advantage. Suppose we only need the first solution and some solutions are close to the root:

  • Depth-first search may enter a branch with a huge number of nodes and no solution, or even an infinite branch (in a sliding puzzle, for example, the same moves can be repeated forever), and never come back.
  • Breadth-first search never does this. It examines all the states at distance 1, then all at distance 2, and so on, so it finds the solution closest to the root first.

The price is memory. Backtracking only stores the current path, O(h)O(h) nodes. Breadth-first search stores the whole frontier of the tree, which can grow exponentially with the depth: a tree of degree mm has mdm^d nodes at depth dd. On random instances of the 8-puzzle (see the next lesson), plain breadth-first search expanded about 84,000 states on average to find the shortest solution. A good heuristic reduced that to about 1,300.


Branching: the heuristic function​

The branching function (or branching heuristic) decides which node to develop next. At every moment, the algorithm selects the best available node at any level of the tree, according to an estimate of how close it is to a (good) solution. Some vocabulary:

  • Live nodes: nodes that have been generated but not yet expanded. They wait in the data structure.
  • E-node (expanding node): the live node currently being expanded.
  • Dead nodes: nodes that have been expanded, or pruned.

Branching algorithms make most sense when the goal is to find a solution and stop (the first one, or the optimal one with good bounds). If the whole tree must be developed anyway (for example, to list all the solutions), the order does not matter much and backtracking is usually better, because it needs far less memory and has no data structure overhead.

The data structure: a priority queue​

The general scheme is the same as breadth-first search, with the FIFO queue replaced by a priority queue (usually implemented as a heap), ordered by the heuristic value. Extracting the best node and inserting a new one both cost O(log⁡k)O(\log k), where kk is the number of live nodes. In Java, the class is java.util.PriorityQueue.

ExplorationJava structure
Depth-firstRecursion (or ArrayDeque used as a stack)
Breadth-first (B&B without branching function)A FIFO queue, such as ArrayDeque or LinkedList through the Queue interface
Best-first (B&B with branching function)PriorityQueue

Consequences of a limited heap​

The number of live nodes can be enormous. A classic heap implemented on a fixed-size array can only hold a limited number of them; in Java, PriorityQueue grows automatically, but eventually the program runs out of memory. Either way, if we decide to discard live nodes because there is no room for them:

  • we are pruning without control, not because the node is proven useless but because it does not fit;
  • with a poor heuristic, the discarded nodes may be the good ones;
  • the algorithm may miss the solution (or the optimal solution) even though it exists.

This is why the pruning must be based on guarantees, which is the role of bounds.


Bounding: the pruning function​

A pruning function prevents the development of states that do nothing to find the solution. A state can be pruned when it:

  1. does not lead to any solution (it is infeasible), or
  2. does not lead to a better solution than the best one already known, or
  3. is a repeated development (the same state was already generated through another path).

Pruning is not exclusive to branch and bound: the same ideas can be added to depth-first or breadth-first search, as we did in backtracking. What branch and bound adds is the systematic use of bounds combined with the best-first order.

Lower and upper bounds​

For a minimization problem:

  • The lower bound c^(x)\hat{c}(x) of a node xx is an optimistic estimate: no solution below xx can cost less than c^(x)\hat{c}(x). It is usually the cost already accumulated plus an optimistic estimate of the cost still to come.
  • The upper bound UU is the cost of the best complete solution found so far (or of a solution built quickly at the start). The optimum cannot cost more than UU.

The pruning rule is then

c^(x)≥U  ⇒  prune x\hat{c}(x) \ge U \;\Rightarrow\; \text{prune } x

since even in the best case, the subtree of xx cannot improve on what we already have. For a maximization problem everything is mirrored: the estimate is an optimistic upper bound, the benchmark is the best value found so far (a lower bound), and a node is pruned when its estimate is less than or equal to that value.

What makes a good bound​

  • It must be optimistic (never worse than the true best value below the node). An estimate that is sometimes too pessimistic can prune the branch that contains the optimum, and the algorithm silently returns a worse solution.
  • It must be cheap to compute. If computing the estimate is as hard as solving the problem, nothing is gained.
  • It should be as tight as possible (close to the true value). The tighter it is, the more nodes are pruned.

These goals conflict: tighter bounds are usually more expensive. A good B&B algorithm finds a balance.

The initial pruning limit​

Before the search starts, UU can be set to +∞+\infty. It is much better to start with the cost of some valid solution obtained quickly, for example by a greedy algorithm. Every node whose estimate is already worse than that solution is pruned from the very beginning. In the task assignment example, the initial limit is the cheaper of the two diagonals of the cost matrix, which are always valid assignments.


General scheme​

The following scheme (used throughout the course, and in the package topics.branchandbound.utils of the course repository) solves a minimization problem. Each node stores a heuristic value, which is its lower bound; for a complete solution, the heuristic value must be its exact cost.

protected Heap nodeHeap; // live nodes, ordered by heuristic value
protected Node bestNode; // best solution found so far
protected Node rootNode; // initial state
protected int globalUpperBound; // cost of bestNode (the pruning limit)

public void branchAndBound(Node initialNode) {
nodeHeap.insert(initialNode);
globalUpperBound = initialNode.initialValuePruneLimit();

while (!nodeHeap.empty() && nodeHeap.estimateBest() < globalUpperBound) {
Node currentNode = nodeHeap.extractBestNode();
List<Node> children = currentNode.expand();
for (Node child : children) {
if (child.isSolution()) {
int solutionCost = child.getHeuristicValue();
if (solutionCost < globalUpperBound) { // a better solution
globalUpperBound = solutionCost;
bestNode = child;
}
} else if (child.getHeuristicValue() < globalUpperBound) {
nodeHeap.insert(child); // still promising
} // otherwise: pruned
}
}
}

Several details are worth noticing:

  • The loop condition nodeHeap.estimateBest() < globalUpperBound stops the whole search as soon as the best live node cannot improve the current solution. Since the heap is ordered, every other live node is at least as bad, so they can all be discarded at once.
  • Children are pruned when they are generated (they are not even inserted), and the limit becomes stricter every time a better solution is found.
  • The heuristic value plays two roles: it orders the heap (branching) and it is compared with the limit (bounding). This is only correct if it is a true lower bound.
  • Repeated states. The Heap class can remember the nodes already expanded and refuse to insert a repeated one. This avoids infinite loops in problems such as sliding puzzles. To make the check fast, the expanded states should be kept in a HashSet (lookup in O(1)O(1)), not scanned one by one.

The classes involved​

The framework separates what is common to every problem from what is specific:

  • BranchAndBound: the general algorithm above. A concrete problem (MyProblem) extends it and only creates the root node.
  • Heap: the priority queue of live nodes, plus the record of expanded nodes (used to detect repetitions and to rebuild the path from the root to the solution, following the parent of each node).
  • Node: an abstract state. A concrete state (MyNode) extends it and implements:
    • calculateHeuristicValue(): the lower bound of the state;
    • expand(): the list of children;
    • isSolution(): whether the state is a complete solution;
    • initialValuePruneLimit(): the initial limit (by default, Integer.MAX_VALUE).

Writing a new B&B algorithm therefore reduces to designing the state, its children, and above all its heuristic.

ProofBest-first branch and bound stops at the optimum

Branch and bound and A*​

If the heuristic value of a node is "cost already paid" plus "optimistic estimate of the cost still to pay",

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

best-first branch and bound becomes the famous A* search algorithm (Hart, Nilsson and Raphael, 1968), used in route planning, video games and robotics. When hh never overestimates the remaining cost (an admissible heuristic), the first solution extracted from the priority queue is optimal.

A common mistake is to order the nodes only by the estimate of the remaining cost, h(x)h(x), forgetting the cost already paid. The search becomes a greedy best-first search: it reaches a solution very quickly, but not necessarily the best one. In the 8-puzzle we measured this effect: ordering by hh alone found solutions with about 65 moves on average, while ordering by g+hg + h found the optimal ones, with about 22 moves (see the next lesson).

ProofA* with an admissible heuristic finds an optimal path

Backtracking or branch and bound?​

Comparing the two techniques is not easy; it depends on the problem and on the quality of the available heuristics.

BacktrackingBranch and bound
ExplorationDepth-firstBreadth-first or best-first
StructureRecursion stackQueue or priority queue of live nodes
MemoryLow: O(h)O(h), only the current pathHigh: may store an exponential number of live nodes
Infinite or very deep branchesMay get lost in themNever gets lost (finds the shallowest solution first)
Overhead per nodeVery lowCreating node objects, heap operations, computing bounds
Best suited forEnumerating all solutions; problems with no good heuristic; solutions in the leavesOptimization with good bounds; finding one solution quickly; shallow solutions

As a rule of thumb:

  • If you need all the solutions, or the whole tree must be developed, backtracking is usually better.
  • If you need one solution and it may be close to the root, or you need the optimum and you have a good bound, branch and bound is usually better.
  • Both can, and should, use pruning.

In the worst case both explore an exponential number of nodes: a good heuristic changes the practical behavior, not the theoretical complexity.


Branch and bound in practice​

  • Integer linear programming. The solvers used in logistics, airline crew scheduling or energy planning (CPLEX, Gurobi, CBC, HiGHS) solve integer programs by branch and bound: the bound comes from solving the problem without the integrality constraints, which is easy, and the branches fix variables to integer values.
  • Traveling salesman. The Concorde solver has found optimal tours through tens of thousands of cities by combining branch and bound with cutting planes.
  • Planning and games. A* and its variants find routes in maps and paths for characters in video games.
  • Computer vision. Branch and bound is used to search efficiently over all possible positions of an object in an image, as in the video Optimal Landmark Detection using Shape Models and Branch and Bound included in the course materials.
  • Scheduling, cutting and packing. Assigning jobs to machines, cutting stock with minimum waste, or packing objects into the fewest containers are classic B&B applications.

Self-check​

1. First solution near the root. True or false: "If we only search for the first solution, and there are solution states near the root, the best choice is usually backtracking."

False. Backtracking may enter a deep (or infinite) branch without solutions and never come back. Breadth-first branch and bound finds the solutions closest to the root first.

2. Infinite branches. True or false: "With backtracking it is possible to enter a branch with many nodes that do not reach any solution, or even one that has no end."

True. That is precisely one of the advantages of exploring breadth-first.

3. The whole tree. True or false: "If you must develop the whole tree, backtracking is usually better than branch and bound."

True. If every node must be visited anyway, the order brings no benefit, and backtracking uses much less memory and has less overhead per node.

4. Data structures. Which Java structure is the most appropriate for branch and bound without a branching function? And with one?

Without a branching function (pure breadth-first): a FIFO Queue. With a branching function that prioritizes the best estimates: a PriorityQueue.

5. Pruning. The pruning function prevents the development of states that (a) are repeated developments, (b) do not lead to better solutions, (c) do not lead to any solution, (d) all of them. Which is correct? And which technique can use pruning: backtracking, branch and bound, or both?

(d), all of them. And both techniques can use pruning.

6. Pessimistic estimates. In a minimization problem, a student's lower bound sometimes returns a value higher than the true best cost below the node. What can go wrong?

A node whose subtree contains the optimum may be pruned, because its estimate looks worse than the current best solution. The algorithm would finish and silently return a suboptimal solution. Bounds must be optimistic.

7. Order of exploration. In which order is the tree of states developed by backtracking? And by branch and bound?

Backtracking develops it depth-first. Branch and bound generates all the children of a node before moving on, which is breadth-first; with a branching heuristic, it becomes best-first.

Common mistakes
  • Using a bound that is not optimistic. It can prune the branch that contains the optimal solution.
  • Taking as initial limit a value that is not a real solution. It must come from a valid solution (or be infinite).
  • Expanding a node without comparing it again with the limit. The limit may have improved since the node was inserted; the loop condition estimateBest() < globalUpperBound takes care of it.

Key ideas​

  • Branch and bound explores the same implicit tree as backtracking, but generates all the children of a node and keeps the live nodes in a data structure.
  • With a FIFO queue it is breadth-first; with a priority queue ordered by a branching heuristic it is best-first, and it can jump to the most promising node at any level.
  • Bounds are optimistic estimates. A node is pruned when its bound cannot beat the best solution found so far; starting with a good initial limit prunes from the very beginning.
  • Bounds must be optimistic, cheap and tight. With f=g+hf = g + h and an admissible hh, best-first B&B is the A* algorithm.
  • Branch and bound is usually better for optimization with good bounds and for shallow solutions; backtracking is better for enumerating and when memory is limited.

The next lesson applies the technique to task assignment, the 0/1 knapsack, sliding puzzles, rectangle placement and the N-queens problem.

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.