Algorithms · Backtracking: N-Queens, Subset Sum, Graph Colouring and Hamiltonian Cycle
What backtracking is
Backtracking is a systematic way of searching a state-space tree: a tree whose root is the empty partial solution, whose internal nodes are partial solutions, and whose leaves are either complete solutions or dead ends. We grow a solution one component at a time; as soon as a partial solution cannot be extended to a valid solution, we abandon ("prune") that whole subtree and return to the most recent choice point to try the next alternative. That return step is the backtrack.
Two ingredients make backtracking more than brute force:
- Incremental construction — we never build a full candidate and then test it; we test each component the moment it is added.
- Bounding / feasibility function — a predicate on a partial solution that is true only if the partial solution can still be completed. If is false we prune. A correct bounding function must never prune a partial solution that could lead to a solution (it may be conservative: it can fail to prune, which only costs time).
Backtracking vs brute force. Brute force enumerates all candidates and checks each one at the end. Backtracking enumerates candidates in a tree and checks prefixes, so entire subtrees die early. The worst case is the same (both may be exponential), but the pruned tree is usually far smaller. Example: 8-queens has placements of 8 queens in 8 columns if we allow any row per column; brute force checks all of them, backtracking with the column/row/diagonal test visits only a few thousand nodes.
General template (recursive form; the loop is over the choices for the next component):
BACKTRACK(k): # k = index of next component to fix
if k > n: # all n components fixed
report solution x[1..n]
return
for each value v in domain of component k:
if FEASIBLE(x[1..k-1], v): # bounding function
x[k] = v
BACKTRACK(k+1)
# implicit undo: x[k] is overwritten on next iteration
The iterative form uses an explicit stack and is equivalent. The recursion depth is at most (the number of components), so the space is for the recursion stack plus whatever the feasibility test needs — this is the key advantage over dynamic programming on the same problems.
Two standard tree shapes (know both, GATE uses both):
- Fixed-tuple / n-ary tree: every node has the same branching factor; depth is fixed at . N-Queens and graph colouring use this (component = column / vertex ).
- Variable-tuple / binary tree: at each level we make a yes/no decision, so the tree is binary and depth is . Subset sum uses this (include or exclude element ).