Backtracking
Backtracking makes choices one step at a time (choose, explore, unchoose) and steps back as soon as a path can't work; with pruning, the 8-queens puzzle finds all 92 solutions in 2057 calls instead of checking 16777216 placements.
Put 8 queens on an 8 × 8 board, no two in the same row, column or diagonal: how many ways are there? One queen per row, 8 columns to choose for each: 8⁸ = 16777216 placements, and you could check them one by one. But once the queen in row 1 is in column 0 and the one in row 2 is in column 0 too, nothing in the other 6 rows can save it, so there's no point trying. That's backtracking: make choices one step at a time, and the moment a path can't work, step back and change the choice. Searching 8 queens this way takes 2057 calls.
The decision tree: one choice per step
Draw "what can be chosen at each step" as a tree: the root is nothing chosen yet, each child is one choice, and a path from the root to a leaf is a whole answer. This is the decision tree. Backtracking walks this tree depth first: going down makes a choice, at a leaf the answer is recorded, then the last choice is undone and it goes back up a level to try the next one.
1void dfs(int k) { // now fixing place k2 if (k == n) { // complete: record the answer3 for (int i = 0; i < n; i++) printf("%d ", path[i]);4 printf("\n");5 return;6 }7 for (int i = 1; i <= n; i++) {8 if (used[i]) continue; // already used: not allowed9 path[k] = i; used[i] = 1; // choose10 dfs(k + 1); // explore11 used[i] = 0; // unchoose12 }13}
Finding the permutations of 1 2 3 in the order of this decision tree (depth first, smaller numbers first at each level), which permutation is found 4th?
After recording 1 2 3, which is the next new node the backtracking reaches?
The template: choose, explore, unchoose
Nearly every backtracking search looks the same:
1void dfs(step) {2 if (complete) { record the answer; return; }3 for (each choice at this step) {4 if (not allowed) continue;5 choose; // change the state6 dfs(next step);7 unchoose; // change it back, so the next choice starts from the same place8 }9}
Permutations: path holds what's been chosen, and used[i] says whether i is taken.
1#include <stdio.h>2 3int n = 3, path[10], used[10];4 5void dfs(int k) { // now fixing place k6 if (k == n) { // complete: record the answer7 for (int i = 0; i < n; i++) printf("%d ", path[i]);8 printf("\n");9 return;10 }11 for (int i = 1; i <= n; i++) {12 if (used[i]) continue; // already used: not allowed13 path[k] = i; used[i] = 1; // choose14 dfs(k + 1); // explore15 used[i] = 0; // unchoose16 }17}18 19int main(void) {20 dfs(0);21 return 0;22}
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
path[k] needs no undoing: the next choice simply overwrites it. used[i] must go back to 0, or the later branches think i is still taken.
The unchoose, used[i] = 0, is missing. What does it print?
1#include <stdio.h>2 3int n = 3, path[10], used[10];4 5void dfs(int k) {6 if (k == n) {7 for (int i = 0; i < n; i++) printf("%d ", path[i]);8 printf("\n");9 return;10 }11 for (int i = 1; i <= n; i++) {12 if (used[i]) continue;13 path[k] = i; used[i] = 1;14 dfs(k + 1);15 }16}17 18int main(void) {19 dfs(0);20 return 0;21}
Put the 3 lines "choose, explore, unchoose" in order so the program prints all 6 permutations of 1 2 3.
used[i] = 0;dfs(k + 1);path[k] = i; used[i] = 1;
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
Subsets and combinations: in or out
In a permutation, each level picks which number comes next. Subsets choose another way: each number has just two choices, in or out. The decision tree is a full binary tree: 8 leaves for 3 numbers, 2ⁿ for n.
1#include <stdio.h>2 3int a[] = {1, 2, 3}, n = 3, path[10], len = 0;4 5void dfs(int k) { // decide whether a[k] is in6 if (k == n) {7 printf("{ ");8 for (int i = 0; i < len; i++) printf("%d ", path[i]);9 printf("}\n");10 return;11 }12 path[len++] = a[k]; // choose: a[k] in13 dfs(k + 1);14 len--; // unchoose15 dfs(k + 1); // a[k] out16}17 18int main(void) {19 dfs(0);20 return 0;21}
{ 1 2 3 }
{ 1 2 }
{ 1 3 }
{ 1 }
{ 2 3 }
{ 2 }
{ 3 }
{ }
| Problem | What each level decides | Answers | Time |
|---|---|---|---|
| Permutations | Which unused number goes in place k | n! | O(n · n!) |
| Subsets | Whether the k-th number is in | 2ⁿ | O(n · 2ⁿ) |
| Combinations (k of n) | Where the next number starts (only forward) | C(n, k) | O(k · C(n, k)) |
There are that many answers, so backtracking can't be faster than that. What it can save is the branches that will never give an answer.
Printing the subsets of {1, 2, 3} with this step's program ("in" first, then "out"), which one is printed 3rd?
How many subsets do 5 numbers have? And how many ways are there to pick 2 of them?
Combinations: 2 out of 4
✓Choose k numbers from 1 to n and print every way, smallest first. To avoid repeats, the next number is only chosen from start onward. Complete dfs.
1 2 1 3 1 4 2 3 2 4 3 4
1#include <stdio.h>2 3int n = 4, k = 2, path[10], len = 0;4 5void dfs(int start) {6 // with k chosen, print them; otherwise for i from start to n: choose i, dfs(i + 1), unchoose7}8 9int main(void) {10 dfs(1);11 return 0;12}
Pruning: don't go down a path that can't work
Pruning checks before choosing: with this choice made, can an answer still come out? If not, continue, and that whole subtree is never walked. The earlier you prune, the more you save.
N-queens: row r gets one queen, trying columns 0 to n − 1; any column in the same column or diagonal as an earlier queen is skipped. On one "\" diagonal r − c is the same, on one "/" diagonal r + c is the same, so three arrays record which columns and diagonals are taken, and each check is O(1).
1#include <stdio.h>2 3int n, solutions;4long calls;5int col[20], d1[40], d2[40]; // columns, "/" diagonals r + c, "\" diagonals r - c + n - 16 7void place(int r) {8 calls++;9 if (r == n) { solutions++; return; }10 for (int c = 0; c < n; c++) {11 if (col[c] || d1[r + c] || d2[r - c + n - 1]) continue; // prune12 col[c] = d1[r + c] = d2[r - c + n - 1] = 1; // choose13 place(r + 1);14 col[c] = d1[r + c] = d2[r - c + n - 1] = 0; // unchoose15 }16}17 18int main(void) {19 printf(" n sols calls no pruning nⁿ\n");20 for (n = 4; n <= 8; n++) {21 solutions = 0;22 calls = 0;23 place(0);24 long all = 1;25 for (int i = 0; i < n; i++) all *= n;26 printf("%2d %4d %10ld %14ld\n", n, solutions, calls, all);27 }28 return 0;29}
n sols calls no pruning nⁿ 4 2 17 256 5 10 54 3125 6 4 153 46656 7 40 552 823543 8 92 2057 16777216
8 queens: without pruning there are 16777216 placements to check; with it, the whole tree has only 2057 nodes. Backtracking's worst case is still exponential (N-queens is about O(n!)), and pruning can't change that, but it cuts the search actually done by several orders of magnitude.
In exams: exam papers seldom ask for backtracking code itself; they ask you to trace N-queens, or "how many permutations do n numbers have", "how many subsets". In interviews, permutations, subsets, combinations, combination sum and N-queens are nearly all this one template: draw the decision tree, then be clear what each level chooses, when it's complete, and what can be pruned.
4 queens has 2 answers. The first puts the queens in columns 1 3 0 2, row by row. What is the second answer the backtracking finds?
0 2 1 3 and 3 0 2 1 both put two queens on the same diagonal.Squares on a "/" diagonal share r + c; squares on a "\" diagonal share r − c (plus n − 1 so the index is never negative). Fill in s so the program prints how many answers 4 to 8 queens have.
1#include <stdio.h>2 3int n, solutions;4int col[20], d1[40], d2[40];5 6void place(int r) {7 if (r == n) { solutions++; return; }8 for (int c = 0; c < n; c++) {9 int s = , t = r - c + n - 1;10 if (col[c] || d1[s] || d2[t]) continue;11 col[c] = d1[s] = d2[t] = 1;12 place(r + 1);13 col[c] = d1[s] = d2[t] = 0;14 }15}16 17int main(void) {18 for (n = 4; n <= 8; n++) {19 solutions = 0;20 place(0);21 printf("%d ", solutions);22 }23 printf("\n");24 return 0;25}
r - c gives negative indexes, and c just repeats the column check and lets diagonals through.Combination sum (with pruning)
✓Choose numbers from 2, 3 and 5 (the same one may be chosen again) adding up to 8, and print every way (numbers smallest first). The array is sorted: once adding a[i] goes over 8, the later ones are bigger, so just break.
2 2 2 2 2 3 3 3 5
1#include <stdio.h>2 3int a[] = {2, 3, 5}, n = 3, target = 8, path[20], len = 0;4 5void dfs(int start, int sum) {6 // sum == target: print; otherwise for i from start: break if sum + a[i] > target;7 // choose a[i], dfs(i, sum + a[i]) (it may be chosen again), unchoose8}9 10int main(void) {11 dfs(0, 0);12 return 0;13}
Summary
Backtracking: one path at a time, back up when it goes nowhere
- The decision tree: one choice per level, root to leaf is one answer
- The template: complete, record it; otherwise for each choice: choose, explore, unchoose
- Forget to unchoose and the later branches see the wrong state
- Prune: check before choosing, and skip whole subtrees that can't work
1for (int i = 0; i < n; i++) {2 if (i not allowed) continue;3 choose i; dfs(k + 1); unchoose i;4}