AlgoViz

Backtracking

medium 20 min

Backtracking builds an answer one choice at a time and abandons a partial answer the moment it cannot work.

Where it shows up

The same pattern appears across everyday software.

  • Sudoku and puzzle solvers

    Solvers fill the next empty cell with a digit that does not clash with its row, column and box, and undo it when they get stuck. With good pruning (try the cell with the fewest options first) even hard 9 × 9 puzzles solve in milliseconds.

  • Chess and game engines

    Game-tree search makes a move, explores the replies, then takes the move back on the board. Alpha-beta pruning is backtracking's pruning idea applied to games: it skips lines that cannot change the final choice.

  • Regular expression engines

    Many regex engines, including Python's re module, match by backtracking: when one way of matching a part of the pattern fails later on, they go back and try another. Badly written patterns can make this exponential, a bug known as catastrophic backtracking.

  • Compilers and parsers

    Some parsers try one grammar rule, and if the input does not fit, rewind to where they started and try the next rule. Packrat parsers add memoisation to the same idea so each position is parsed once per rule.

  • Scheduling and timetables

    Building exam timetables, shift rotas or meeting schedules is constraint satisfaction: assign a slot, check the rules (no clashes, rest periods), and undo when an assignment leads nowhere. Constraint solvers combine this search with smarter pruning.

  • SAT solvers and verification

    SAT solvers decide whether a logic formula can be made true by guessing a variable's value, propagating the consequences and backtracking on a conflict (the DPLL and CDCL algorithms). They power hardware verification, package dependency resolution and planning.