Every project / Techy

๐ŸŒ€ Maze Maker & Solver

Generate a random maze with depth-first search, then solve it with breadth-first search.

Maze Maker & Solver running
Language
Python
Level
Advanced
Category
Techy
โ–ถ Try it & remix

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).

SettingStarts atFileWhat it does
WIDTH, HEIGHT18, 9main.pysize in cells
SEEDNonemain.pyput a number here to get the same maze every time
WALL, OPEN"โ–ˆ", " "maze.pycharacters for walls and paths

Files

FileLines
main.py18where the program starts
maze.py82imported by main.py

Challenges

Each one is a bit harder than the last. Teachers: these make good assignment instructions.

  1. Make a bigger maze by changing WIDTH and HEIGHT.
  2. Set SEED to a number so you get the same maze every time.
  3. Count how many dead ends the maze has.
  4. Solve it with depth-first search instead, and compare how many cells each one explores.
  5. Let the player walk through the maze by typing n/s/e/w.