Introduction
Finding a route through a maze is graph search: cells are nodes and moves are edges. Running three classic algorithms side by side shows clearly why BFS guarantees the shortest path, why DFS may explore less but gives no guarantee, and why A* with a good heuristic does both well.
Problem statement
Objectives
- Model a grid as a graph with a neighbours generator
- Implement BFS with a deque, DFS with a stack and A* with a heap
- Rebuild paths from parent links
- Compare algorithms empirically
Features
- Multiple named mazes per input
- BFS, DFS and A* side by side
- Shortest path drawn on the maze
- Explored-cell counts
- Validation and no-path detection
Concepts demonstrated
- Graph search
- Shortest paths
- Heuristics
- Priority queues
System architecture
Maze pads ragged rows, finds S and E and yields valid neighbours. Each search records came_from links and rebuild walks them back from the exit. BFS explores in rings with a deque; DFS uses a list as a stack; A* orders a heap by f = g + h and, among equal f, prefers deeper cells (larger g), which heads straight for the goal in open areas. Outdated heap entries are skipped by comparing g with the best known cost.
Folder structure
Complete source code
main.py
What each file does
- main.py
- The Maze class, the three search algorithms, path drawing and the report.
How to run it
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
; Small maze ######### #S..#...# #.#.#.#.# #.#...#.# #.#####.# #...#..E# ######### ; Open room ############## #S...........# #............# #............# #............# #...........E# ############## ; Dead end ####### #S..#E# ###.#.# #...#.# ####### ; No exit marked ##### #S..# #####
Testing
- Run
python main.py < tests/sample-input.txtand compare withtests/expected-output.txt. - In the small maze all three algorithms find a path of length 14.
- In the open room A* explores only 16 cells while BFS explores 60 to find the same 15-step path.
- The dead-end maze reports no path and the maze without an E is rejected.
Common errors
DFS reports a longer path than BFS
That's expected: DFS doesn't guarantee shortest paths. Use BFS or A* when length matters.
A* explores as many cells as BFS
Break ties between equal f values in favour of larger g, as this solver does.
Possible improvements
- Add weighted cells (mud costs 3) and Dijkstra's algorithm
- Allow diagonal moves with an octile heuristic
- Generate random mazes with recursive backtracking
Additional challenges
- 1Animate the search frontier step by step in the terminal.
- 2Find the longest shortest path in a maze (its diameter).
- 3Solve mazes with keys and doors (state = position + keys held).
Built and tested it yourself? Mark it to update your dashboard.