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 ; 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 for the stack.
At a glance
| Problem | Tree | Worst-case time | Main pruning |
|---|---|---|---|
| Permutations | Degree | None | |
| Subset sum | Binary, height | Sum exceeds the target, or cannot reach it | |
| N-queens | Degree , height | Row and diagonal checks in | |
| Knight's tour | Degree 8, height | Visited squares; Warnsdorff ordering | |
| Graph coloring | Degree , height | Adjacent vertex with the same color | |
| Task assignment | Degree | Cost so far reaches the best cost | |
| Magic squares | Degree | Each line must add up to 15 | |
| Sudoku | Degree at most 9 | , empty cells | Row, 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
Questions, or something wrong?
Errors, suggestions and public questions open a form on GitHub, visible to everyone.