Backtracking is depth-first search over the space of DECISIONS. At each step you choose one option, recurse to continue building the candidate, then UNDO the choice and try the next option. The undo is the name of the algorithm: because you cleanly revert, one shared working state serves the entire exploration, instead of copying state at every branch.
The skeleton is three lines inside a loop: choose, explore, unchoose. Everything else is problem dressing. The art is pruning, detecting early that a partial candidate can never become a solution and cutting that whole subtree. Good pruning is the difference between a sudoku solver that finishes instantly and one that runs until the heat death of the universe.
The universal skeleton + two classics
function backtrack(state, choices) {
if (isSolution(state)) { record(state); return; } // or return true to stop early
for (const choice of choices(state)) {
if (!isValid(state, choice)) continue; // PRUNE impossible branches
apply(state, choice); // CHOOSE
backtrack(state, choices(state)); // EXPLORE
undo(state, choice); // UNCHOOSE, the crucial step
}
}
// Subsets of [1,2,3]:
function subsets(nums) {
const out = [], path = [];
function dfs(start) {
out.push([...path]); // every prefix IS a subset
for (let i = start; i < nums.length; i++) {
path.push(nums[i]); // choose
dfs(i + 1); // explore (i+1: no reuse)
path.pop(); // unchoose
}
}
dfs(0);
return out; // [[], [1], [1,2], [1,2,3], [1,3], [2], [2,3], [3]]
}
// N-queens: place one queen per row; prune if the column/diagonal clashes
function solveNQueens(n) {
const cols = new Set(), diag1 = new Set(), diag2 = new Set();
let solutions = 0;
function place(row) {
if (row === n) { solutions++; return; }
for (let col = 0; col < n; col++) {
const d1 = row - col, d2 = row + col;
if (cols.has(col) || diag1.has(d1) || diag2.has(d2)) continue; // PRUNE
cols.add(col); diag1.add(d1); diag2.add(d2); // choose
place(row + 1); // explore
cols.delete(col); diag1.delete(d1); diag2.delete(d2); // unchoose
}
}
place(0);
return solutions;
}| Operation / case | Cost | Notes |
|---|---|---|
| Subsets (2ⁿ leaves) | O(2ⁿ · n) | copying each subset costs up to n |
| Permutations (n! leaves) | O(n! · n) | — |
| N-queens | ≤ O(n!) | pruning makes it dramatically faster in practice |
| Space | O(depth) | path + recursion, state is shared & undone |