Skip to main content

Backtracking: Classic Problems

23 min readRead first: The Backtracking Scheme

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:

What you will learn in this lesson
  • How to design the state representation and feasibility checks for eight classic backtracking problems.
  • How O(1)O(1) 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.
ProblemSchemeWhat it illustrates
PermutationsAll solutionsMarking used elements; tree whose degree decreases by one
Subset sumAll solutionsBinary tree (take it or leave it); look-ahead pruning
N-queensFirst solution and all solutionsClever representation; O(1)O(1) feasibility tests
Knight's tourFirst solutionHuge trees; the effect of ordering the candidates
Graph coloringAll solutionsConstraint satisfaction
Task assignmentBest solutionOptimization with bound pruning
Magic squaresAll solutionsPruning as soon as a constraint is complete
SudokuFirst solutionConstraint 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 nn distinct elements (for example 0,1,2,30, 1, 2, 3), 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
...
The tree of permutations of 0, 1 and 2: each level fills one position with an unused element–001012020211101021212022020121210nothing placedposition 0: 3 optionsposition 1: 2 optionsposition 2: 1 option
The tree of permutations of three elements. Each level fills one position with an element not used yet, so the levels have 3, 6 and 6 nodes, and the leaves are the 3! = 6 permutations.

Design.

  • Solution vector: sol[0..n-1], where sol[k] is the element placed in position kk. 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 nn.
  • Candidates: every element not used yet. A boolean array used answers "is element ii already in the permutation?" in O(1)O(1).
  • 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 nn children, each of them n−1n - 1, and so on: the tree has 1+n+n(n−1)+⋯+n!1 + n + n(n-1) + \dots + n! nodes. For n=4n = 4 that is 1+4+12+24+24=651 + 4 + 12 + 24 + 24 = 65 calls, which we confirmed by counting. The time is O(n!)O(n!) (there are n!n! solutions to print, so no algorithm can do better) and the extra space is O(n)O(n).

🧠 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 44, 4⋅3=124 \cdot 3 = 12, 4⋅3⋅2=244 \cdot 3 \cdot 2 = 24 and 2424 nodes: 64 nodes below the root, of which 24 are leaves, one per permutation (4!=244! = 24).


Subset sum​

Problem. Given a set of nn distinct positive integers and a value cc, find all subsets whose elements add up to cc. For example, with {1,2,3,4,5}\{1, 2, 3, 4, 5\} and c=10c = 10:

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 kk decides about element vkv_k.
  • Each element has only two options: take it or leave it. The tree is binary, of height nn.
  • We do not need a solution array of values. The current sum is enough to check the constraint, plus a boolean array taken if we want to print the subsets.
  • Since all numbers are positive, we can prune in two ways:
    • feasibility: do not take vkv_k if it would make the sum exceed cc;
    • look-ahead: do not leave vkv_k out if, without it, even taking all the remaining elements could not reach cc. An array remaining[k] with the sum of vk,…,vn−1v_k, \dots, v_{n-1} (computed once at the start) answers this in O(1)O(1).
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);
}
}
Subset sum with 1, 2, 3, 4, 5 and target 10: the pruned tree has 25 nodes+1+2+3+4+4+3+4+4+5+2+3+4+5+4+3+40136106371481510025951026037decide 1decide 2decide 3decide 4decide 5node: current sum · solid: take · dashed: leave · green: sum 10 · red: dead end · 25 nodes, not 63
The pruned search tree for {1, 2, 3, 4, 5} and c = 10. Each node shows the current sum; solid edges take the next number and dashed edges leave it. The search reaches the 3 solutions with 25 calls instead of the 63 nodes of the full tree.

Effect of pruning. The full binary tree for n=5n = 5 has 26−1=632^6 - 1 = 63 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: O(2n)O(2^n) time and O(n)O(n) space. This problem is NP-complete: no polynomial algorithm is known. (If cc is small, a dynamic programming table of size n×cn \times c decides whether a solution exists in pseudo-polynomial time, like the 0/1 knapsack.)


N-queens​

Problem. Place nn queens on an n×nn \times n 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 n×nn \times n 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:

sol[j]=i  ⟺  there is a queen in column j and row i\texttt{sol}[j] = i \iff \text{there is a queen in column } j \text{ and row } i

This representation guarantees by construction that no two queens share a column. The level of the tree is the column jj being filled.

Constant-time checks​

To know whether square (i,j)(i, j) is attacked, we keep three boolean arrays:

  • a[i] (size nn): there is a queen in row ii.
  • b[i + j] (size 2n−12n - 1): there is a queen in the diagonal where i+ji + j is constant (going up to the right). The sum ranges from 0 to 2n−22n - 2.
  • c[i - j + n - 1] (size 2n−12n - 1): there is a queen in the diagonal where i−ji - j is constant (going down to the right). The difference ranges from −(n−1)-(n-1) to n−1n - 1, so we add n−1n - 1 to get a valid index.

Square (i,j)(i, j) 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 O(1)O(1).

Code​

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

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 n=4n = 4 the search goes like this (rows and columns numbered from 0):

  1. Column 0, row 0. Column 1: rows 0 and 1 are attacked; try row 2. Column 2: every row is attacked. Back.
  2. 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.
  3. Column 0, row 1. Column 1: row 3. Column 2: row 0. Column 3: row 2. Solution (1,3,0,2)(1, 3, 0, 2).
The first-solution search for 4 queens: 9 nodes generated until the solution (1, 3, 0, 2)( )(0)(0,2)dead end(0,3)(0,3,1)dead end(1)(1,3)(1,3,0)(1,3,0,2)each number: the row of the queen in that column♛♛♛♛col 0col 1col 2col 3solution (1, 3, 0, 2)
The trace for n = 4 as a tree. Each node lists the rows of the queens placed so far, column by column; the two dead ends force the search back to column 0, and the third branch reaches the solution.

The first-solution version stops here after generating 9 nodes. The all-solutions version continues and finds the second (and last) solution, (2,0,3,1)(2, 0, 3, 1), which is the mirror image of the first.

How many solutions?​

nn123456789101112
Solutions100210440923527242,68014,200

There are no solutions for n=2n = 2 and n=3n = 3. 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: O(n!)O(n!). The diagonal checks prune most of it (for n=8n = 8, 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 n=14n = 14. A full video walkthrough is available in N Queen Problem Using Backtracking Algorithm.

Exploiting symmetry​

The board has symmetries: reflecting a solution vertically (row ii becomes row n−1−in - 1 - i) 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 nn, it is therefore enough to try only the first n/2n/2 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 nn, the middle row of the first column is its own mirror image and must be explored separately, without doubling.) We measured it:

nnNodes, whole boardNodes, upper halfSolutions (2 × half)
82,0571,02992
12856,189428,09514,200
1427,358,55313,679,277365,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 n×nn \times n 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:

The 8 possible moves of a knight from a central square, in the order of the arrays a and b32415867♞
The 8 moves of a knight from a central square, numbered in the order of the displacement arrays a and b.

Design.

  • Board: int[][] board, where board[x][y] == 0 means the square has not been visited and board[x][y] == i means it was visited at step ii. 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} and b = {-1, -2, -2, -1, 1, 2, 2, 1}. Move kk goes from (x,y)(x, y) to (x+ak,y+bk)(x + a_k, y + b_k). The order of the moves is arbitrary, but it has a big effect on the running time.
  • Level: the step number ii. The starting square is step 1, so the first recursive call is for step 2, and the tour is complete when step n2n^2 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 n2n^2, so a naive bound is O(8n2)O(8^{n^2}). 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):

BoardStartResultRecursive calls
5×55 \times 5corner (0,0)(0, 0)304 different tours (all solutions)1,735,079
5×55 \times 5(1,4)(1, 4)no tour exists (all solutions)1,829,421
8×88 \times 8corner (0,0)(0, 0)first tour found27,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 8×88 \times 8 board the first tour is found with 64 calls, one per square, without a single step back. The same happens on 20×2020 \times 20 (400 calls) and 50×5050 \times 50 (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 mm 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 vv. Level vv decides the color of vertex vv.
  • Candidates: the mm colors.
  • Feasibility: color colcol is valid for vertex vv 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 (0,1,0,1,2)(0, 1, 0, 1, 2).

Complexity. O(mn)O(m^n) nodes in the worst case, and O(n)O(n) per feasibility check, so O(n⋅mn)O(n \cdot m^n). 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 m=2m = 2 colors? And with m=3m = 3?

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 nn agents and nn tasks. Each agent must perform exactly one task and each task must be performed by exactly one agent. A matrix gives the cost C[i][j]C[i][j] of agent ii performing task jj. Find the assignment with the minimum total cost.

For example, with 3 agents and 3 tasks:

Agent \ Task012
01095
1234
2876

There are 3!=63! = 6 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 5+2+7=145 + 2 + 7 = 14.

Design. A solution is a permutation (agent ii 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 n!n! permutations. With it, the savings are huge. On random n×nn \times n matrices with costs between 1 and 99, we measured:

nnCalls without pruningCalls with pruning
8109,6011,279
109,864,101 (0.2 s)12,739 (7 ms)
11108,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 3×33 \times 3 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 kk decides the number in cell kk.
  • 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 1515 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 9×99 \times 9 grid, partially filled, so that every row, every column and every 3×33 \times 3 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] and box[b][v], say whether the digit vv is already in row rr, column cc or box b=3⌊r/3⌋+⌊c/3⌋b = 3 \lfloor r/3 \rfloor + \lfloor c/3 \rfloor.
  • 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 cellNodes generatedTime in our run
First empty cell49,5597 ms
Fewest candidates10,10236 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.)

Common mistakes
  • Checking the queens with loops. Arrays of used rows and diagonals make each check O(1)O(1).
  • 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​

ProblemTreeWorst-case timeMain pruning
PermutationsDegree n,n−1,…,1n, n-1, \dots, 1O(n!)O(n!)None (all leaves are solutions)
Subset sumBinary, height nnO(2n)O(2^n)Sum exceeds cc; remaining elements cannot reach cc
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})Board limits and 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, 1, height 9O(9!)O(9!)Each line must add up to 15 when complete
SudokuDegree at most 9, one level per empty cellO(9e)O(9^e) for ee empty cellsRow, column and box checks; fewest candidates first

Practice​

  • 👑 Measure the O(1)O(1) check. In N-queens for n=12n = 12, compare counting all solutions with a loop-based conflict check versus boolean arrays for rows and diagonals. How much faster is the O(1)O(1) 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 8×88 \times 8 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 4×44 \times 4 board.
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.