Lecture 11

Recursion with backtracking

MCS 275 Spring 2024
Emily Dumas

View as:   Presentation   ·   PDF-exportable  ·   Printable

Lecture 11: Recursion with backtracking

Reminders and announcements:

  • Project 1 autograder opens Mon.
  • Project 1 due next Fri at 11:59pm.
  • Project 2 will be posted Mon Feb 12.

Plan

  • Maze API
  • Write maze solver (recursion with backtracking)
  • Experiment with it
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.

Let's write this in Python

depth_first_maze_solution(M,path=None):

Arguments:

  • M - a Maze object to be solved (read only)
  • path - a list of Point2 objects

Returns: Either

  • List of Point2 objects (solution extending path), or
  • None (if no solution exists that extends path)

Maze coordinates

Maze coordinates

Image support

Class Maze can save an instance as SVG (.save_svg(fn)) or PNG (.save_png(fn)).

The latter requires a module called Pillow we'll discuss later. Can install with:

python3 -m pip install pillow

References

Same suggested references as Lecture 9.

Revision history

  • 2023-02-10 Finalization of the 2023 lecture this was based on
  • 2024-02-02 Initial publication
  • 2024-02-05 Reference link fixed
  • 2024-02-06 Fix project 1 deadline