Learn / Recursion and backtracking
Rat in a maze
Walk a grid from a start cell, trying each neighbour that is open and not already on the current path. Mark a cell when you step on it and unmark it when you step back. That enumerates every simple path, which answers all, longest and exists questions. For the shortest path, breadth-first search is the better tool.
How to recognise it
- A grid or graph must be walked without revisiting a cell on the same path.
- The question asks for every path, the longest path, or whether a long enough path exists.
- Some cells are blocked, or are made unsafe by nearby cells.
The idea in one picture
Unroll a ball of string as you walk the maze. Each cell the string touches is on your path and cannot be entered again. At a dead end, wind the string back to the last junction and try another way.
Template: walk, mark, unmark
function walk(cell, path):
if cell is the goal: record or measure path; return
mark cell
for each neighbour that is open and unmarked:
walk(neighbour, path + step)
unmark cell
Which tool for which question
| Question | Tool |
|---|---|
| every path | backtracking |
| longest path | backtracking, keep the best |
| is there a path of at least k | backtracking, stop at the first success |
| shortest path, all steps cost 1 | breadth-first search |
| a tour that visits every square | backtracking with a good move order (Warnsdorff) |
Common mistakes
- Marking cells as visited forever, which hides paths that reuse a cell on a different branch.
- Using backtracking for shortest paths on large grids.
- Checking bounds after reading the cell, which reads outside the grid.
Problems
- Rat in a Mazemediumguide ready
- Find shortest safe route in a path with landminesmediumguide ready
- Find if there is a path of more than k length from a sourcemediumguide ready
- Longest Possible Route in a Matrix with Hurdlesmediumguide ready
- Print all possible paths from top left to bottom right of a mXn matrixmediumguide ready
- The Knight’s tour problemhardguide ready