Skip to main content

Summary: Backtracking

Everything on one page, to review the chapter before moving on.

Key ideas​

  • Backtracking performs a depth-first search of an implicit tree of states, generating nodes only when they are reached (The Backtracking Scheme).
  • A solution is a vector of decisions (x1,…,xn)(x_1, \dots, x_n); each level of the tree fixes one decision.
  • The pattern is choose, explore, unchoose: every change must be undone when going back.
  • Two schemes: first solution (stop as soon as one is found) and all solutions (enumerate, count or keep the best).
  • Pruning and a good ordering of the candidates make the difference between a usable algorithm and brute force.
  • The worst-case time is usually exponential or factorial; the memory is only O(h)O(h) for the stack.

At a glance​

ProblemTreeWorst-case timeMain pruning
PermutationsDegree n,n−1,…,1n, n-1, \dots, 1O(n!)O(n!)None
Subset sumBinary, height nnO(2n)O(2^n)Sum exceeds the target, or cannot reach it
N-queensDegree nn, height nnO(n!)O(n!)Row and diagonal checks in O(1)O(1)
Knight's tourDegree 8, height n2n^2O(8n2)O(8^{n^2})Visited squares; Warnsdorff ordering
Graph coloringDegree mm, height nnO(n⋅mn)O(n \cdot m^n)Adjacent vertex with the same color
Task assignmentDegree n,n−1,…,1n, n-1, \dots, 1O(n!)O(n!)Cost so far reaches the best cost
Magic squaresDegree 9,8,…,19, 8, \dots, 1O(9!)O(9!)Each line must add up to 15
SudokuDegree at most 9O(9e)O(9^e), ee empty cellsRow, column and box checks

All the problems are in Classic Problems.

When to use it​

  • To enumerate all the solutions, or to count them.
  • For hard combinatorial problems with no good bound, or when memory is limited.
  • If dynamic programming applies, it is usually better. If you need the optimum and have a good bound, consider branch and bound.
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.