Skip to content
Python project #20Advanced

Maze Solver

Find paths through grid mazes and compare breadth-first search, depth-first search and A* by path length and cells explored.

Estimated time
~4 hours to build
Files
4 files · 306 lines
Technologies
Python 3, collections.deque, heapq

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

Read mazes separated by blank lines, with walls '#', open cells '.', one start 'S' and one exit 'E', and optional ';' name lines. For each maze, run BFS, DFS and A* (Manhattan heuristic), draw the shortest path with '*' and print each algorithm's path length and number of cells explored. Report mazes with no path, and reject mazes without exactly one S and one E.

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

TextProject tree
maze-solver/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

140 lines
Pythonmain.py
"""Maze Solver: compares breadth-first search, depth-first search and A* on grid mazes.
Input: mazes separated by blank lines, '#' for walls, '.' for open cells, 'S' start, 'E' exit.
A line starting with ';' names the maze that follows. Moves are up, down, left and right.
"""
import heapq
import sys
from collections import deque
Cell = tuple[int, int]
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)] # up, right, down, left
class Maze:
def __init__(self, rows: list[str]):
width = max(len(r) for r in rows)
self.grid = [r.ljust(width, "#") for r in rows] # ragged rows are padded with walls
self.height, self.width = len(self.grid), width
self.start = self.find("S")
self.end = self.find("E")
def find(self, ch: str) -> Cell:
spots = [(r, c) for r, row in enumerate(self.grid) for c, x in enumerate(row) if x == ch]
if len(spots) != 1:
raise ValueError(f"the maze needs exactly one '{ch}' (found {len(spots)})")
return spots[0]
def neighbours(self, cell: Cell):
r, c = cell
for dr, dc in MOVES:
nr, nc = r + dr, c + dc
if 0 <= nr < self.height and 0 <= nc < self.width and self.grid[nr][nc] != "#":
yield nr, nc
def rebuild(came_from: dict[Cell, Cell | None], end: Cell) -> list[Cell]:
path, cell = [], end
while cell is not None:
path.append(cell)
cell = came_from[cell]
return path[::-1]
def bfs(maze: Maze) -> tuple[list[Cell] | None, int]:
came_from: dict[Cell, Cell | None] = {maze.start: None}
queue = deque([maze.start])
while queue:
cell = queue.popleft()
if cell == maze.end:
return rebuild(came_from, cell), len(came_from)
for nxt in maze.neighbours(cell):
if nxt not in came_from:
came_from[nxt] = cell
queue.append(nxt)
return None, len(came_from)
def dfs(maze: Maze) -> tuple[list[Cell] | None, int]:
came_from: dict[Cell, Cell | None] = {maze.start: None}
stack = [maze.start]
while stack:
cell = stack.pop()
if cell == maze.end:
return rebuild(came_from, cell), len(came_from)
for nxt in reversed(list(maze.neighbours(cell))):
if nxt not in came_from:
came_from[nxt] = cell
stack.append(nxt)
return None, len(came_from)
def astar(maze: Maze) -> tuple[list[Cell] | None, int]:
def h(cell: Cell) -> int:
return abs(cell[0] - maze.end[0]) + abs(cell[1] - maze.end[1]) # Manhattan distance
came_from: dict[Cell, Cell | None] = {maze.start: None}
cost = {maze.start: 0}
# Entries are (f, -g, cell): among equal f values, prefer the deeper cell, which heads for the goal.
heap = [(h(maze.start), 0, maze.start)]
expanded = 0
while heap:
_, neg_g, cell = heapq.heappop(heap)
g = -neg_g
if g > cost[cell]:
continue # an outdated heap entry
expanded += 1
if cell == maze.end:
return rebuild(came_from, cell), expanded
for nxt in maze.neighbours(cell):
if g + 1 < cost.get(nxt, 10 ** 9):
cost[nxt] = g + 1
came_from[nxt] = cell
heapq.heappush(heap, (g + 1 + h(nxt), -(g + 1), nxt))
return None, expanded
def draw(maze: Maze, path: list[Cell]) -> None:
rows = [list(r) for r in maze.grid]
for r, c in path[1:-1]:
rows[r][c] = "*"
for row in rows:
print(" " + "".join(row))
def blocks(text: str) -> list[tuple[str, list[str]]]:
result, name, block = [], None, []
for line in text.splitlines() + [""]:
if line.startswith(";"):
name = line[1:].strip()
elif line.strip():
block.append(line.rstrip())
elif block:
result.append((name or f"Maze {len(result) + 1}", block))
name, block = None, []
return result
def main() -> None:
for name, rows in blocks(sys.stdin.read()):
print(f"== {name} ({len(rows[0])}x{len(rows)}) ==")
try:
maze = Maze(rows)
except ValueError as error:
print(f" Invalid maze: {error}\n")
continue
results = {"BFS": bfs(maze), "DFS": dfs(maze), "A*": astar(maze)}
best, _ = results["BFS"]
if best is None:
print(f" No path from S to E ({results['BFS'][1]} reachable cells explored).\n")
continue
draw(maze, best)
print(f" {'Algorithm':<10}{'Path length':>12}{'Cells explored':>16}")
for algo, (path, explored) in results.items():
print(f" {algo:<10}{len(path) - 1:>12}{explored:>16}")
print()
if __name__ == "__main__":
main()

What each file does

main.py
The Maze class, the three search algorithms, path drawing and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
== Small maze (9x7) ==
#########
#S**#***#
#.#*#*#*#
#.#***#*#
#.#####*#
#...#..E#
#########
Algorithm Path length Cells explored
BFS 14 21
DFS 14 16
A* 14 21
== Open room (14x7) ==
##############
#S***********#
#...........*#
#...........*#
#...........*#
#...........E#
##############
Algorithm Path length Cells explored
BFS 15 60
DFS 15 29
A* 15 16
== Dead end (7x5) ==
No path from S to E (7 reachable cells explored).
== No exit marked (5x3) ==
Invalid maze: the maze needs exactly one 'E' (found 0)
Input
; Small maze
#########
#S..#...#
#.#.#.#.#
#.#...#.#
#.#####.#
#...#..E#
#########

; Open room
##############
#S...........#
#............#
#............#
#............#
#...........E#
##############

; Dead end
#######
#S..#E#
###.#.#
#...#.#
#######

; No exit marked
#####
#S..#
#####

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/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

  1. 1Animate the search frontier step by step in the terminal.
  2. 2Find the longest shortest path in a maze (its diameter).
  3. 3Solve mazes with keys and doors (state = position + keys held).

Built and tested it yourself? Mark it to update your dashboard.