Planning a maze solver
User wants a Python program to solve mazes using BFS and DFS, likely expecting code snippets. They haven't specified the maze format, so I’ll assume it's a 2D grid represented in a text file, featuring walls and open spaces. I need to implement both BFS for the shortest path and DFS for any path, keeping the code detailed but concise. The maze will be represented as a list of strings or a 2D list, using 'S' for start, 'E' for exit, '#' for walls, and ' ' for passable areas. I'll ensure it's self-contained by defining the necessary classes and functions.Designing the maze solver
I'm considering that the user likely wants a Python script that reads from a maze file, like 'maze.txt', or potentially takes user input directly. To keep it straightforward, I’ll decide on reading from a text file. We will first define functions to handle the maze grid, and then provide a main example for demonstration. The BFS will use a queue, and I’ll choose an iterative approach for DFS to avoid recursion depth issues. Path reconstruction will use stored parent nodes, and I’ll outline functions for parsing the maze, getting neighbors, and marking paths while addressing edge cases like multiple start or end points.Implementing BFS for the maze
I need to handle coordinates for the BFS algorithm, using deque from the collections module for efficient queue management. I’ll represent the maze as a list of lists filled with characters, stripping newlines and ignoring empty lines. The BFS function will start from the initial position and explore each possible direction until it finds the goal. I'll manage visited positions with a set and track parents for path reconstruction. If the goal isn’t reached, the function will return None, indicating no path found.Reconstructing paths in BFS and DFS
For the BFS, I have the reconstruct_path function that builds the path from the goal to the start using a parent dictionary. If a parent can't be found during the process, it returns None. For DFS, I’ll adjust my approach slightly. Using a stack for depth-first search, I’ll pop positions and check for the goal, similarly leveraging the neighbor list. I need to ensure that if the goal is found, I return using the reconstruct_path function, maintaining a clean structure throughout the implementation.Finalizing the maze solver implementation
I’m developing the overlay_path function to mark the found path in the maze, using a copy of the maze to do so. For displaying, I’ll implement print_maze to print each row neatly. In the main function, I'll use argparse to optionally load a maze from a file or provide a default maze. The parse_maze function will extract the start and end points. I need to highlight complexities: BFS has O(V+E), while DFS is the same but may not find the shortest path. I’ll ensure clarity, but keep the explanation concise as per user’s request. Below is a self‑contained Python program that solves a 2D maze with both BFS (shortest path) and DFS (any path).
Maze format (text file or inline):
# = wall
S = start
E = exit
- space (
) or other non-# characters = open cells
Example maze:
#########
#S # #
# ### # #
# # #E#
#########
Full Python Program
#!/usr/bin/env python3
from collections import deque
import argparse
def parse_maze(lines):
"""
Convert list of strings into a grid and find S (start) and E (end).
"""
maze = [list(line.rstrip('\n')) for line in lines if line.strip('\n')]
start = end = None
for r, row in enumerate(maze):
for c, ch in enumerate(row):
if ch == 'S':
start = (r, c)
elif ch == 'E':
end = (r, c)
if start is None:
raise ValueError("Maze has no start 'S'")
if end is None:
raise ValueError("Maze has no end 'E'")
return maze, start, end
def get_neighbors(r, c, rows, cols):
"""
Return 4-connected neighbors (up, right, down, left).
"""
for dr, dc in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
return (nr, nc)
def bfs(maze, start, goal):
"""
Breadth-First Search: returns shortest path from start to goal
as a list of (row, col) tuples, or None if no path exists.
"""
rows, cols = len(maze), len(maze[0])
queue = deque([start])
visited = set([start])
parent = {} # child -> parent
while queue:
r, c = queue.popleft()
if (r, c) == goal:
return reconstruct_path(parent, start, goal)
for dr, dc in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
if maze[nr][nc] != '#' and (nr, nc) not in visited:
visited.add((nr, nc))
parent[(nr, nc)] = (r, c)
queue.append((nr, nc))
return None # no path
def dfs(maze, start, goal):
"""
Depth-First Search: returns some path from start to goal
as a list of (row, col) tuples, or None if no path exists.
"""
rows, cols = len(maze), len(maze[0])
stack = [start]
visited = set([start])
parent = {} # child -> parent
while stack:
r, c = stack.pop()
if (r, c) == goal:
return reconstruct_path(parent, start, goal)
# Order controls which direction DFS explores first
for dr, dc in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
if maze[nr][nc] != '#' and (nr, nc) not in visited:
visited.add((nr, nc))
parent[(nr, nc)] = (r, c)
stack.append((nr, nc))
return None # no path
def reconstruct_path(parent, start, goal):
"""
Reconstruct path from 'start' to 'goal' using the parent dictionary.
"""
path = []
current = goal
while current != start:
path.append(current)
current = parent.get(current)
if current is None:
return None # no path (shouldn't happen if called correctly)
path.append(start)
path.reverse()
return path
def overlay_path(maze, path):
"""
Return a new maze grid with the path marked by '.' characters.
Keeps 'S' and 'E' unchanged.
"""
maze_copy = [row[:] for row in maze]
for (r, c) in path:
if maze_copy[r][c] not in ('S', 'E'):
maze_copy[r][c] = '.'
return maze_copy
def print_maze(maze):
for row in maze:
print(''.join(row))
def main():
parser = argparse.ArgumentParser(
description="Solve a maze using BFS (shortest path) and DFS."
)
parser.add_argument(
"file",
nargs="?",
help="Path to maze text file (optional). If omitted, uses a built-in example."
)
args = parser.parse_args()
if args.file:
with open(args.file, 'r') as f:
lines = f.readlines()
else:
# Built-in example maze
lines = [
"#########",
"#S # #",
"# ### # #",
"# # #E#",
"#########",
]
maze, start, goal = parse_maze(lines)
print("Original maze:")
print_maze(maze)
print()
bfs_path = bfs(maze, start, goal)
if bfs_path:
print(f"BFS found a path of length {len(bfs_path)}:")
print_maze(overlay_path(maze, bfs_path))
print()
else:
print("BFS: No path found.\n")
dfs_path = dfs(maze, start, goal)
if dfs_path:
print(f"DFS found a path of length {len(dfs_path)}:")
print_maze(overlay_path(maze, dfs_path))
else:
print("DFS: No path found.")
if __name__ == "__main__":
main()
How to use
- Save the code as
maze_solver.py.
- Create a maze file, e.g.
maze.txt, in the format described above.
- Run:
python maze_solver.py maze.txt
or, to use the built‑in example:
python maze_solver.py