Lecture 15

Recursion with backtracking

MCS 275 Spring 2022
David Dumas

Lecture 15: Recursion with backtracking

Course bulletins:

  • Project 2 description available.
  • Project 2 due 6pm central Friday 25 February.
  • Check out the recursion sample code.

Plan

  • Review backtracking algorithm to solve a maze
  • 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?

We'll solve a maze like this using 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.

If we ever receive a solution from a recursive call, we return it immediately.

Algorithm depth_first_maze_solution:

Input: a maze and a path under consideration (partial progress toward solution).

  1. If the path is a solution, just return it.
  2. Otherwise, enumerate possible next steps that don't go backwards.
  3. For each of the possible next steps:
    • Make a new path by adding this next step to the current one.
    • Make a recursive call to attempt to complete this path to a solution.
    • If recursive call returns a solution, we're done. Return it immediately.
    • (If recursive call returns None, continue the loop.)
  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

Same suggested references as Lecture 13.

Revision history

  • 2022-02-14 Initial publication