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

QuestionTool
every pathbacktracking
longest pathbacktracking, keep the best
is there a path of at least kbacktracking, stop at the first success
shortest path, all steps cost 1breadth-first search
a tour that visits every squarebacktracking 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

0 of 6 solved

Check yourself

Why unmark a cell when the walk steps back from it?

For the shortest path in an unweighted grid, which method is better than backtracking?

The longest simple path in a grid has no fast general method. What does that mean for the code?