How Backtracking Solves Sudoku
Sudoku is a constraint satisfaction problem: every row, column, and 3×3 box must contain the digits 1 through 9 exactly once. A backtracking solver treats it as a search - fill the next empty cell with a candidate digit, and if that choice ever makes the puzzle unsolvable, undo it and try the next candidate.
This is the same "guess, check, undo" pattern used in the N-Queens Problem, just with a much richer set of constraints per cell (row, column, and box) instead of a single conflict check.
Time & Space Complexity
- Worst Case TimeO(9^m)
- Space (Recursion)O(m)
- Constraint CheckO(1)
* m = number of empty cells. Real puzzles solve far faster than the worst case thanks to early pruning.
Speeding It Up
- ✓Most-Constrained Cell FirstFilling the cell with the fewest valid candidates first prunes the tree faster.
- ✓Bitmask ConstraintsTracking used digits per row/column/box as bitmasks makes validity checks O(1).
- ✓Constraint PropagationTechniques like naked singles fill obvious cells before any guessing begins.