Solve N-Queens and Sudoku by trial and error, undoing each wrong move.
4 algorithms3 problems
4 algorithms. Each one builds on the last.
Try a digit, move on, and undo it when the grid gets stuck.
O(9^B) time · O(1) for a 9 by 9 board spaceVisualizeThese four pages solve puzzles with a function that calls itself on a smaller piece of the problem. Three of them search: they make a choice, go deeper, and undo the choice when it leads nowhere. Backtracking is the standard tool for constraint puzzles, for listing permutations and subsets, and for interview problems such as word search and combination sum.
Every page reduces the puzzle to one step plus a smaller puzzle of the same kind, with a base case that stops the calls. The call stack remembers where each step was taken. In backtracking, a branch that fails returns false and its caller tries the next option, so every board that shares the bad choice is thrown away the moment one clash appears.
If the puzzle has one fixed sequence of steps, as Hanoi does, plain recursion is enough. If you must choose among options and some choices only fail later, you need backtracking, and the order you try options in and how early you check for clashes decide how fast it runs. A frequent bug is forgetting to undo a choice on the way back, which leaves stale marks that block later branches. For the shortest route through a grid, use breadth-first search instead.