Kodewick
Start learning →
Backtracking46 / 50

Backtracking

Lesson 46 of 50 · Part 9 · Algorithm design · about 18 minutes

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.

empty
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}

The permutations of 1 2 3: each level fixes one place, and a number already used can't be chosen again. Down is a choice, back up is undoing it; the 6 leaves are the 6 permutations
Choose one

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?

Choose one

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.

main.c
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}
Output
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.

Guess the outputA wrong guess is fine

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 in orderDrag, or use the arrows

Put the 3 lines "choose, explore, unchoose" in order so the program prints all 6 permutations of 1 2 3.

  1. used[i] = 0;
  2. dfs(k + 1);
  3. path[k] = i; used[i] = 1;
Should print
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.

{ }

The subsets of {1, 2, 3}: level k decides whether the k-th number is in; left is in, right is out
main.c
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}
Output
{ 1 2 3 }
{ 1 2 }
{ 1 3 }
{ 1 }
{ 2 3 }
{ 2 }
{ 3 }
{ }
ProblemWhat each level decidesAnswersTime
PermutationsWhich unused number goes in place kn!O(n · n!)
SubsetsWhether the k-th number is in2ⁿ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.

Choose one

Printing the subsets of {1, 2, 3} with this step's program ("in" first, then "out"), which one is printed 3rd?

Choose one

How many subsets do 5 numbers have? And how many ways are there to pick 2 of them?

Exercise 1

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.

It should print
1 2
1 3
1 4
2 3
2 4
3 4
exercise1.c
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}
Output
Press Run or Ctrl+Enter

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).

0123row 0    row 1    row 2    row 3    

Backtracking 4 queens: row by row, the next column when one is blocked, and back up a row when a whole row is blocked
main.c
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}
Output
 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.

Choose one

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?

Fill inTap one to fill a blank; tap a blank to take it back

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}
Exercise 2

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.

It should print
2 2 2 2
2 3 3
3 5
exercise2.c
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}
Output
Press Run or Ctrl+Enter

Summary

Take-away

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}