Every project / Techy
๐ Maze Maker & Solver
Generate a random maze with depth-first search, then solve it with breadth-first search.
- Language
- Python
- Level
- Advanced
- Category
- Techy
What you'll learn
- Depth-first search
- Breadth-first search
- Stacks & queues
- 2D grids
- Sets & dictionaries
How it works
- The grid has cells at odd positions, with walls in between.
- make_maze() uses depth-first search: wander randomly knocking down walls, and back up at dead ends.
- solve() uses breadth-first search, which spreads out one step at a time, so the first path to reach the end is the shortest.
- Walking backwards through came_from rebuilds that path, which is drawn with dots.
Knobs to turn
These settings are near the top of the code. Remix it, change one, and watch what happens. The preview updates as you type (press โถ Run for Python).
| Setting | Starts at | File | What it does |
|---|---|---|---|
WIDTH, HEIGHT | 18, 9 | main.py | size in cells |
SEED | None | main.py | put a number here to get the same maze every time |
WALL, OPEN | "โ", " " | maze.py | characters for walls and paths |
Files
| File | Lines | |
|---|---|---|
main.py | 18 | where the program starts |
maze.py | 82 | imported by main.py |
Challenges
Each one is a bit harder than the last. Teachers: these make good assignment instructions.
- Make a bigger maze by changing WIDTH and HEIGHT.
- Set SEED to a number so you get the same maze every time.
- Count how many dead ends the maze has.
- Solve it with depth-first search instead, and compare how many cells each one explores.
- Let the player walk through the maze by typing n/s/e/w.