Lecture 15

Recursion with backtracking

MCS 275 Spring 2021
Emily Dumas

Lecture 15: Recursion with backtracking

Course bulletins:

  • Project 2 description available.
  • Project 2 due 6pm CST Friday, February 26.
  • Check out the recursion sample code.

Plan

  • Talk about solving mazes with recursion
  • Present a module for working with mazes
  • Implement the maze solver

Recursion with backtracking

How do you solve a maze?

Recursion with backtracking

How do you solve a maze?

My guess at your mental algorithm:

  • Try something (move around but don't return to anywhere you've visited).
  • If you reach a dead end, go back a bit and reconsider which way to go at a recent intersection.

An algorithm that formalizes this is recursion with backtracking.

We make a function that takes:

  • The maze
  • The path so far

Its goal is to add one more step to the path, never backtracking, and call itself to finish the rest of the path.

But if it hits a dead end, it needs to notice that and backtrack.

Backtracking

Backtracking is implemented through the return value of a recursive call.

Recursive call may return:

  • A solution, or
  • None, indicating that only dead ends were found.

Algorithm depth_first_maze_solution:

Input: a maze and a path under consideration (partial progress toward solution). Initially, the path is just the starting point.

  1. If the path is a solution, just return it.
  2. Otherwise, enumerate possible next steps (not returning to a location already in the path).
  3. For each of the possible next steps:
    • Add it to the path under consideration.
    • Make a recursive call to attempt to complete this path to a solution.
    • If recursive call returns a solution, return it immediately.
    • Otherwise, remove the last step from the path and go to the next iteration.
  4. If we get to this point, every continuation of the path is a dead end. Return None.

Depth first

This method is also called a depth first search for a path through the maze.

Here, depth first means that we always add a new step to the path before considering any other changes (e.g. going back and modifying an earlier step).

Maze coordinates

Maze coordinates

References

No changes to the references from Lecture 13

Revision history

  • 2021-02-15 Initial publication