Maze Solving
This chapter covers the maze solving problem: given a maze, is there a path from the start to the exit? We solve it three times: with recursive backtracking, with an explicit stack, and with a queue. All three give the same answer. They differ in the order in which they explore the maze.
After reading this chapter, you should be able to:
- Represent a rectangular maze as a two-dimensional array
- Solve the maze with recursive backtracking, using a visited array to make the search terminate
- Explain how the recursive search uses the call stack to hold its unfinished cells
- Implement the maze search with an explicit stack in place of recursion
- Check a maze search against the edge cases of the maze path problem
- Explain how replacing the stack with a queue changes the order in which the search explores cells
- Trace the recursive, stack, and queue searches on a small maze
- Analyze the time and space cost of the three searches in terms of rows and columns
You can download the accompanying code for this chapter: starter and solution.
Sections
- Why Mazes?
- Representing a Maze
- The Maze Path Problem
- Asking About a Cell
- A First Recursive Search
- Remembering Where We Have Been
- Returning Through a Path
- Tracing Recursive Backtracking
- Searching with an Explicit Stack
- Tidying Up the Stack-Based Search
- The Stack Search in Code
- Swapping in a Queue
- Tracing the Queue Search
- The Cost of the Three Searches