← chapter

Backtracking: N-Queens, subsets, permutations

Build a candidate incrementally; abandon it the moment it's doomed. Depth-first search + PRUNING.

The move: try — recurse — undo

Watch it search

Green ♛ = placed on a safe square · red = attacked → pruned · orange = backtrack (undo). Every red square dismisses a whole branch unexamined.

Pruning vs brute force

N=12: brute force 8.9 trillion arrangements, backtracking 10 million nodes → 880,000× fewer.

Pruning is the algorithm

Takeaway

Don't ask "how do I generate all candidates" — ask "how early can I reject one." Get the UNDO exactly right, or later branches see corrupted state. Next: two pointers & sliding window — O(n²) scans → O(n) passes.