backtracking
Backtracking sits next to branch and bound, both appear on the web supplement Earlier, the stacks chapter uses a rat in a maze as an application Those two chapters are the same idea seen from different angles
Backtracking is search with undo
The pattern
def subsets(items):
result, path = [], []
def walk(start):
result.append(list(path))
for i in range(start, len(items)):
path.append(items[i])
walk(i + 1)
path.pop()
walk(0)
return result
Three items produce eight subsets
The pop is the backtrack
Without it, the second branch inherits the first branch’s choices and the answer is garbage
Choose, explore, undo
Every recursive step makes a choice Then it explores what follows Then it undoes the choice so the next branch starts clean
That is why a stack is the natural structure for an iterative version Each stack frame is a decision you can unwind
The maze
The rat in a maze problem asks for a path from entrance to exit At each cell you try a direction If it fails, you come back and try another
That application teaches software engineering principles, not just recursion Keeping the maze state, marking visited cells, and restoring them on failure are all contract problems
Pruning
Stop a branch early when it cannot possibly lead to a valid answer That is the difference between a search that finishes and one that consumes the afternoon
A puzzle solver checks constraints before adding another choice A path finder checks bounds before moving A combination generator skips duplicates before recursing
Cost
Still exponential in the general case No pruning changes the worst case Know the input size before you run it
Backtracking versus branch and bound
Backtracking searches and undoes Branch and bound also tracks a best known answer and discards branches that cannot beat it That extra bookkeeping is what makes hard optimisation problems tractable sometimes
Mistakes
- forgetting the undo
- sharing a mutable result list without copying it
- marking cells visited and never unmarking
- expecting pruning to fix an exponential problem
Exercises
- Write subsets from memory and verify the count for four items
- Add a constraint that only subsets with even sums are kept
- Implement a tiny maze walk with undo on visited cells
- Explain why backtracking needs a stack even when written recursively
What to remember
Backtracking is disciplined trial and error The discipline is the undo
Posted