Backtracking: Classic Problems
This lesson applies the general schemes of backtracking to a series of classic problems. They are ordered from simple to more demanding, and each one illustrates a different aspect of the paradigm:
- How to design the state representation and feasibility checks for eight classic backtracking problems.
- How bookkeeping arrays (rows, columns, diagonals) drastically reduce the cost per node in N-queens and Sudoku.
- How look-ahead pruning (Subset sum), bound pruning (Task assignment), and candidate ordering (Warnsdorff's rule for Knight's tour) shrink huge search trees.
- The trade-off between visiting fewer nodes and spending more time per node.
| Problem | Scheme | What it illustrates |
|---|---|---|
| Permutations | All solutions | Marking used elements; tree whose degree decreases by one |
| Subset sum | All solutions | Binary tree (take it or leave it); look-ahead pruning |
| N-queens | First solution and all solutions | Clever representation; feasibility tests |
| Knight's tour | First solution | Huge trees; the effect of ordering the candidates |
| Graph coloring | All solutions | Constraint satisfaction |
| Task assignment | Best solution | Optimization with bound pruning |
| Magic squares | All solutions | Pruning as soon as a constraint is complete |
| Sudoku | First solution | Constraint satisfaction; choosing the most constrained cell |
The full code of most of these examples, with tests and time measurements, is in the course repository vicegd/algorithms, in the package topics.backtracking.
Permutations
Problem. Given distinct elements (for example ), generate all their orderings:
0 1 2 3
0 1 3 2
0 2 1 3
0 2 3 1
0 3 1 2
0 3 2 1
1 0 2 3
...
Design.
- Solution vector:
sol[0..n-1], wheresol[k]is the element placed in position . All the permutations are built, one after another, in the same array. - Level: the position being filled. The search starts at level 0 (nothing placed) and a permutation is complete at level .
- Candidates: every element not used yet. A boolean array
usedanswers "is element already in the permutation?" in . - Undo: unmark the element when going back, so it becomes available for other positions.
int n; // number of elements
int[] sol; // the permutation being built
boolean[] used; // used[i] == true if element i is already in sol
void permutations(int level) {
if (level == n) // a complete permutation
System.out.println(Arrays.toString(sol));
else
for (int i = 0; i < n; i++)
if (!used[i]) { // element i is still available
used[i] = true; // choose
sol[level] = i;
permutations(level + 1); // explore
used[i] = false; // unchoose
}
}
The call is permutations(0). The order of the output follows the order of the loop, so permutations come out in lexicographic order: 0 1 2 3, 0 1 3 2, 0 2 1 3, 0 2 3 1, ...
Complexity. The root has children, each of them , and so on: the tree has nodes. For that is calls, which we confirmed by counting. The time is (there are solutions to print, so no algorithm can do better) and the extra space is .
🧠 Checkpoint: Size of the tree
Question: How many nodes does the tree of permutations of 4 elements have below the root? How many leaves?
Answer: The levels have , , and nodes: 64 nodes below the root, of which 24 are leaves, one per permutation ().
Subset sum
Problem. Given a set of distinct positive integers and a value , find all subsets whose elements add up to . For example, with and :
1 + 2 + 3 + 4 = 10
1 + 4 + 5 = 10
2 + 3 + 5 = 10
Design.
- The order inside a subset does not matter, so we decide about the elements in order: level decides about element .
- Each element has only two options: take it or leave it. The tree is binary, of height .
- We do not need a solution array of values. The current sum is enough to check the constraint, plus a boolean array
takenif we want to print the subsets. - Since all numbers are positive, we can prune in two ways:
- feasibility: do not take if it would make the sum exceed ;
- look-ahead: do not leave out if, without it, even taking all the remaining elements could not reach . An array
remaining[k]with the sum of (computed once at the start) answers this in .
int[] v; // the numbers (all positive)
int c; // the target sum
boolean[] taken; // taken[k] == true if v[k] is in the current subset
int[] remaining; // remaining[k] = v[k] + v[k+1] + ... + v[n-1]; remaining[n] = 0
void subsets(int level, int sum) {
if (sum == c) // positive numbers: nothing below can also sum c
printSubset(level);
else if (level < v.length) {
if (sum + v[level] <= c) { // option 1: take v[level]
taken[level] = true;
subsets(level + 1, sum + v[level]);
taken[level] = false;
}
if (sum + remaining[level + 1] >= c) // option 2: leave it, if c is still reachable
subsets(level + 1, sum);
}
}
Effect of pruning. The full binary tree for has nodes. With both prunings, the algorithm finds the 3 solutions in 25 calls. On a larger instance (30 random numbers between 1 and 100, target 500, with more than 1.6 million solutions), feasibility pruning alone needed about 402 million calls, and adding the look-ahead test reduced them to about 98 million, roughly four times fewer.
Complexity. In the worst case the binary tree is explored completely: time and space. This problem is NP-complete: no polynomial algorithm is known. (If is small, a dynamic programming table of size decides whether a solution exists in pseudo-polynomial time, like the 0/1 knapsack.)
N-queens
Problem. Place queens on an chessboard so that no queen attacks another. A queen attacks any square in its row, its column or its two diagonals. You can try it interactively in the eight queens puzzle by H. B. Meyer or watch the search in the recursive N-queens visualization by David Galles.
The difficulties are two: finding a good representation of the board, and knowing quickly whether a square is attacked.
Representation
An matrix would work, but it wastes space and makes the checks slow. Since there must be exactly one queen per column, it is enough to store, for each column, the row of its queen:
This representation guarantees by construction that no two queens share a column. The level of the tree is the column being filled.
Constant-time checks
To know whether square is attacked, we keep three boolean arrays:
a[i](size ): there is a queen in row .b[i + j](size ): there is a queen in the diagonal where is constant (going up to the right). The sum ranges from 0 to .c[i - j + n - 1](size ): there is a queen in the diagonal where is constant (going down to the right). The difference ranges from to , so we add to get a valid index.
Square is free if and only if !a[i] && !b[i+j] && !c[i-j+n-1]. Placing or removing a queen updates three positions. Every check and every update is .
Code
- First solution
- All solutions
void backtracking(int j) {
if (j == n) { // the n queens are placed
found = true;
printSolution(); // print (or copy) sol now
} else
for (int i = 0; i < n; i++)
if (!found && !a[i] && !b[i + j] && !c[i - j + n - 1]) {
sol[j] = i; // a queen in column j and row i
a[i] = true; // row used
b[i + j] = true; // diagonal i+j used
c[i - j + n - 1] = true; // diagonal i-j used
backtracking(j + 1);
sol[j] = -1; // leave everything as it was
a[i] = false;
b[i + j] = false;
c[i - j + n - 1] = false;
}
}
void backtracking(int j) {
if (j == n) { // the n queens are placed
count++;
printSolution();
} else
for (int i = 0; i < n; i++)
if (!a[i] && !b[i + j] && !c[i - j + n - 1]) {
sol[j] = i;
a[i] = true;
b[i + j] = true;
c[i - j + n - 1] = true;
backtracking(j + 1);
sol[j] = -1;
a[i] = false;
b[i + j] = false;
c[i - j + n - 1] = false;
}
}
The only difference is the found flag. Note that in the first-solution version the undo step erases sol as the recursion returns, so the solution must be printed or copied when it is found.
Trace for n = 4
With the search goes like this (rows and columns numbered from 0):
- Column 0, row 0. Column 1: rows 0 and 1 are attacked; try row 2. Column 2: every row is attacked. Back.
- Column 1, row 3. Column 2: try row 1. Column 3: every row is attacked. Back to column 2: no more rows. Back to column 1: no more rows. Back to column 0.
- Column 0, row 1. Column 1: row 3. Column 2: row 0. Column 3: row 2. Solution .
The first-solution version stops here after generating 9 nodes. The all-solutions version continues and finds the second (and last) solution, , which is the mirror image of the first.
How many solutions?
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Solutions | 1 | 0 | 0 | 2 | 10 | 4 | 40 | 92 | 352 | 724 | 2,680 | 14,200 |
There are no solutions for and . The classic eight queens puzzle has 92 solutions, which reduce to 12 essentially different ones if rotations and reflections are considered equal. No formula is known for the number of solutions; they are counted by search.
Complexity. Without the diagonal checks, the tree would contain every permutation of the rows: . The diagonal checks prune most of it (for , the algorithm generates 2,057 nodes to find all 92 solutions, out of the 40,320 permutations), but the growth remains exponential. The previous lesson has the measured counts up to . A full video walkthrough is available in N Queen Problem Using Backtracking Algorithm.
Exploiting symmetry
The board has symmetries: reflecting a solution vertically (row becomes row ) gives another solution. Every solution with the first queen in the upper half of the first column has a mirror image with the first queen in the lower half. For even , it is therefore enough to try only the first rows for the first queen and count each solution twice:
void backtracking(int j) {
...
int limit = (j == 0) ? n / 2 : n; // first column: only the upper half
for (int i = 0; i < limit; i++)
...
}
The number of solutions is 2 * count. (For odd , the middle row of the first column is its own mirror image and must be explored separately, without doubling.) We measured it:
| Nodes, whole board | Nodes, upper half | Solutions (2 × half) | |
|---|---|---|---|
| 8 | 2,057 | 1,029 | 92 |
| 12 | 856,189 | 428,095 | 14,200 |
| 14 | 27,358,553 | 13,679,277 | 365,596 |
The work is exactly halved. Using also the rotations and the other reflections of the board (8 symmetries in total), the essentially different solutions can be found with about an eighth of the work, but the bookkeeping is more delicate.
Knight's tour
Problem. A knight must visit every square of an board exactly once, using its usual L-shaped move (two squares in one direction and one in the perpendicular direction). From a square in the middle of the board, it has 8 possible moves:
Design.
- Board:
int[][] board, whereboard[x][y] == 0means the square has not been visited andboard[x][y] == imeans it was visited at step . At the end the board itself shows the tour. - Moves: two arrays with the displacements, for example
a = {2, 1, -1, -2, -2, -1, 1, 2}andb = {-1, -2, -2, -1, 1, 2, 2, 1}. Move goes from to . The order of the moves is arbitrary, but it has a big effect on the running time. - Level: the step number . The starting square is step 1, so the first recursive call is for step 2, and the tour is complete when step has been placed.
- Valid move: inside the board and not visited.
void backtracking(int i, int x, int y) { // place step i, knight at (x, y)
if (i == n * n + 1) // all squares visited
found = true;
else
for (int k = 0; k < 8 && !found; k++) {
int u = x + a[k]; // target square
int v = y + b[k];
if (u >= 0 && u < n && v >= 0 && v < n && board[u][v] == 0) {
board[u][v] = i; // mark
backtracking(i + 1, u, v);
if (!found)
board[u][v] = 0; // unmark, unless we must keep the tour
}
}
}
The condition if (!found) before unmarking keeps the finished tour on the board. Without it, the board would be empty when the search returns.
How big is the tree?
The degree is at most 8 and the height is , so a naive bound is . In practice many moves fall outside the board or on visited squares, but the tree is still enormous. Some measurements (with the move order above):
| Board | Start | Result | Recursive calls |
|---|---|---|---|
| corner | 304 different tours (all solutions) | 1,735,079 | |
| no tour exists (all solutions) | 1,829,421 | ||
| corner | first tour found | 27,241,113 (0.6 s) |
The second row is a good reminder: proving that no solution exists requires exploring the whole pruned tree.
Ordering the candidates: Warnsdorff's rule
In 1823 H. C. von Warnsdorff proposed a simple heuristic: always move to the square from which the knight will have the fewest onward moves. Squares that are hard to reach (corners, edges) are visited first, before they become isolated.
Applied as the order in which backtracking tries the 8 moves (the algorithm is still complete, because it can still go back), the effect is spectacular: on the board the first tour is found with 64 calls, one per square, without a single step back. The same happens on (400 calls) and (2,500 calls). The rule is not infallible (with unlucky tie-breaking it can reach a dead end), which is exactly why it is useful to embed it in a backtracking search rather than use it as a pure greedy algorithm.
This is the general lesson: the order in which candidates are tried can matter more than any pruning.
Graph coloring
Problem. Given an undirected graph and colors, assign a color to every vertex so that no two adjacent vertices share a color. The classic application is coloring a map so that neighboring regions have different colors (the four color theorem states that 4 colors are always enough for a planar map). Other applications include exam timetabling (vertices are exams, edges join exams with common students, colors are time slots) and register allocation in compilers.
Design.
- Solution vector:
color[v]is the color of vertex . Level decides the color of vertex . - Candidates: the colors.
- Feasibility: color is valid for vertex if no neighbor already colored (those with a smaller index) has it.
boolean[][] adj; // adjacency matrix
int m; // number of colors
int[] color; // color[v] = color of vertex v (-1 = not colored yet)
boolean canPaint(int v, int col) {
for (int u = 0; u < v; u++) // only vertices already colored
if (adj[v][u] && color[u] == col)
return false;
return true;
}
void coloring(int v) {
if (v == n)
printColoring();
else
for (int col = 0; col < m; col++)
if (canPaint(v, col)) {
color[v] = col;
coloring(v + 1);
color[v] = -1;
}
}
Example. For a cycle of 5 vertices (each vertex joined to the next, and the last to the first), the algorithm finds no coloring with 2 colors (an odd cycle cannot alternate two colors) and 30 colorings with 3 colors. The first one found is .
Complexity. nodes in the worst case, and per feasibility check, so . Deciding whether a graph can be colored with 3 colors is NP-complete.
🧠 Checkpoint: Coloring a cycle
Question: How many valid colorings does a cycle of 5 nodes have with colors? And with ?
Answer: With 2 colors, none: in a cycle the colors must alternate, which is impossible with an odd number of nodes. With 3 colors, 30 colorings. With 2 colors, the search alternates the colors along the cycle and every branch is pruned at the last node, which is adjacent to two nodes of different colors.
Task assignment
Problem. There are agents and tasks. Each agent must perform exactly one task and each task must be performed by exactly one agent. A matrix gives the cost of agent performing task . Find the assignment with the minimum total cost.
For example, with 3 agents and 3 tasks:
| Agent \ Task | 0 | 1 | 2 |
|---|---|---|---|
| 0 | 10 | 9 | 5 |
| 1 | 2 | 3 | 4 |
| 2 | 8 | 7 | 6 |
There are possible assignments, with costs 19, 21, 17, 21, 14 and 16. The optimum is agent 0 to task 2, agent 1 to task 0 and agent 2 to task 1, with cost .
Design. A solution is a permutation (agent performs task assign[i]), so the structure is the same as for permutations. Since we want the best solution, we use the "all solutions" scheme and keep the best assignment found so far. The greedy approach of giving each agent its cheapest free task does not guarantee the optimum: here it would give agent 0 task 2 (5), agent 1 task 0 (2) and agent 2 task 1 (7), which happens to be optimal, but it is easy to build matrices where it fails.
Bound pruning. All costs are positive, so the cost of a partial assignment can only grow. If the cost so far plus the cost of the next choice already reaches the best complete cost, that branch cannot lead to a better solution and is discarded.
int[][] cost;
int[] assign, bestAssign;
boolean[] taskUsed;
int bestCost = Integer.MAX_VALUE;
void assignTasks(int agent, int costSoFar) {
if (agent == n) { // a complete assignment
if (costSoFar < bestCost) {
bestCost = costSoFar;
bestAssign = assign.clone(); // copy it: undo would erase it
}
} else
for (int task = 0; task < n; task++)
if (!taskUsed[task] && costSoFar + cost[agent][task] < bestCost) {
taskUsed[task] = true;
assign[agent] = task;
assignTasks(agent + 1, costSoFar + cost[agent][task]);
taskUsed[task] = false;
}
}
Without the condition costSoFar + cost[agent][task] < bestCost, this is plain exhaustive search over the permutations. With it, the savings are huge. On random matrices with costs between 1 and 99, we measured:
| Calls without pruning | Calls with pruning | |
|---|---|---|
| 8 | 109,601 | 1,279 |
| 10 | 9,864,101 (0.2 s) | 12,739 (7 ms) |
| 11 | 108,505,112 (1.2 s) | 35,103 (2 ms) |
Both versions return the same optimum. The pruning works better when good solutions are found early, which is why the branch and bound technique explores the most promising nodes first and uses an estimate of the remaining cost, not only the cost accumulated so far.
Magic squares
Problem. Find all the magic squares: the numbers 1 to 9 placed in the 9 cells so that every row, column and diagonal adds up to 15. This is the example that opened the previous lesson.
Design.
- Solution vector:
cell[0..8], the cells read row by row. Level decides the number in cell . - Candidates: the numbers not used yet, marked in a boolean array, as for permutations.
- Feasibility: after placing a number, every line (row, column or diagonal) whose three cells are already filled must add up to 15. A line is complete when its last cell (in the reading order) has been filled.
static final int[][] LINES = {{0,1,2}, {3,4,5}, {6,7,8}, // rows
{0,3,6}, {1,4,7}, {2,5,8}, // columns
{0,4,8}, {2,4,6}}; // diagonals
int[] cell = new int[9];
boolean[] used = new boolean[10];
boolean linesOk(int filled) { // cells 0..filled-1 are filled
for (int[] l : LINES) {
int last = Math.max(l[0], Math.max(l[1], l[2]));
if (last < filled && cell[l[0]] + cell[l[1]] + cell[l[2]] != 15)
return false; // a complete line that does not add up
}
return true;
}
void magic(int k) {
if (k == 9) {
printSquare();
return;
}
for (int v = 1; v <= 9; v++)
if (!used[v]) {
used[v] = true;
cell[k] = v;
if (linesOk(k + 1)) // prune as soon as a line fails
magic(k + 1);
used[v] = false;
cell[k] = 0;
}
}
It finds the 8 magic squares (the rotations and reflections of 2 7 6 / 9 5 1 / 4 3 8) after generating 2,378 nodes, while filling all 9 cells before checking would generate 986,410.
A look-ahead improvement. When two cells of a line are filled, the third one is determined: it must be minus their sum. If that number is outside 1 to 9 or already used, the branch can be pruned before filling the third cell. Even better, the candidates of a cell that completes a line can be reduced to that single value.
Sudoku
Problem. Complete a grid, partially filled, so that every row, every column and every box contains the digits 1 to 9 exactly once.
Design. Sudoku is the N-queens idea applied three times:
- State: the grid, with 0 in the empty cells.
- Constant-time checks: three boolean tables,
row[r][v],col[c][v]andbox[b][v], say whether the digit is already in row , column or box . - Level: one empty cell. Each level tries the digits that are not in its row, column or box.
- Scheme: first solution (a well-posed Sudoku has exactly one).
int[][] grid = new int[9][9]; // 0 = empty
boolean[][] row = new boolean[9][10], col = new boolean[9][10], box = new boolean[9][10];
boolean solve() {
int r = -1, c = -1;
for (int i = 0; i < 81 && r < 0; i++) // first empty cell
if (grid[i / 9][i % 9] == 0) { r = i / 9; c = i % 9; }
if (r < 0) return true; // no empty cell: solved
int b = (r / 3) * 3 + c / 3;
for (int v = 1; v <= 9; v++)
if (!row[r][v] && !col[c][v] && !box[b][v]) {
grid[r][c] = v;
row[r][v] = col[c][v] = box[b][v] = true;
if (solve()) return true; // first solution: stop
grid[r][c] = 0;
row[r][v] = col[c][v] = box[b][v] = false;
}
return false; // no digit fits: go back
}
Before calling solve(), the given digits are written in the grid and marked in the three tables. Here the grid itself is the solution vector, and the undo step (writing 0 again) is skipped once the solution is found, because solve() returns as soon as it succeeds.
Choosing the cell. The code takes the first empty cell. A classic improvement is to take the empty cell with the fewest candidates (the minimum remaining values heuristic): a cell with a single possible digit is filled without branching, and a cell with none reveals a dead end immediately. We tried both versions on a puzzle published in 2012 by Arto Inkala as one of the hardest Sudokus:
| Choice of cell | Nodes generated | Time in our run |
|---|---|---|
| First empty cell | 49,559 | 7 ms |
| Fewest candidates | 10,102 | 36 ms |
The heuristic generates five times fewer nodes, but each node is more expensive, because it counts the candidates of every empty cell. For a single Sudoku both are instantaneous; the lesson is the trade-off between the size of the tree and the cost of each node, which appears in every backtracking algorithm. (Keeping the candidate counts updated incrementally, instead of recounting them, gets the best of both.)
- Checking the queens with loops. Arrays of used rows and diagonals make each check .
- Generating permutations with repeated elements. Mark the elements already used.
- Pruning subset sum only when the sum exceeds the target. Also prune when the remaining elements cannot reach it.
- Not emptying the cell again when backtracking in Sudoku. The next candidates are then checked against a wrong board.
Summary
| Problem | Tree | Worst-case time | Main pruning |
|---|---|---|---|
| Permutations | Degree | None (all leaves are solutions) | |
| Subset sum | Binary, height | Sum exceeds ; remaining elements cannot reach | |
| N-queens | Degree , height | Row and diagonal checks in | |
| Knight's tour | Degree 8, height | Board limits and 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 , height 9 | Each line must add up to 15 when complete | |
| Sudoku | Degree at most 9, one level per empty cell | for empty cells | Row, column and box checks; fewest candidates first |
Practice
- 👑 Measure the check. In N-queens for , compare counting all solutions with a loop-based conflict check versus boolean arrays for rows and diagonals. How much faster is the version?
- 🎯 Look-ahead pruning. Run Subset sum on 25 positive integers with and without the remaining-sum pruning condition. Compare the number of visited nodes.
- 🐴 Candidate ordering. Run Knight's tour on an board with fixed move order versus Warnsdorff's heuristic, and count how many backtracks each one needs to find the first tour.
- 🧩 Most-constrained cell. In Sudoku, trace by hand which empty cell is picked first by the fewest-candidates heuristic on a partially filled board.
Errors, suggestions and public questions open a form on GitHub, visible to everyone.