import sys
from collections import deque
# Directions: up, down, left, right
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def find_start(maze):
"""Find the start position marked 'S'."""
for r in range(len(maze)):
for c in range(len(maze[0])):
if maze[r][c] == 'S':
return (r, c)
return None
def find_end(maze):
"""Find the end position marked 'E'."""
for r in range(len(maze)):
for c in range(len(maze[0])):
if maze[r][c] == 'E':
return (r, c)
return None
def solve_bfs(maze):
"""Solve the maze using BFS (guaranteed shortest path in unweighted graph)."""
rows, cols = len(maze), len(maze[0])
start = find_start(maze)
end = find_end(maze)
if not start or not end:
return None
queue = deque([start])
visited = set([start])
parent = {start: None}
while queue:
curr = queue.popleft()
if curr == end:
# Reconstruct path
path = []
at = curr
while at is not None:
path.append(at)
at = parent[at]
return path[::-1]
r, c = curr
for dr, dc in directions:
nr, nc = r + dr, c + dc
if (0 <= nr < rows and 0 <= nc < cols and
maze[nr][nc] != '1' and (nr, nc) not in visited):
visited.add((nr, nc))
queue.append((nr, nc))
parent[(nr, nc)] = curr
return None
def solve_dfs(maze):
"""Solve the maze using iterative DFS (finds one possible path, not necessarily shortest)."""
rows, cols = len(maze), len(maze[0])
start = find_start(maze)
end = find_end(maze)
if not start or not end:
return None
stack = [start]
visited = set([start])
parent = {start: None}
while stack:
curr = stack.pop()
if curr == end:
# Reconstruct path
path = []
at = curr
while at is not None:
path.append(at)
at = parent[at]
return path[::-1]
r, c = curr
for dr, dc in directions:
nr, nc = r + dr, c + dc
if (0 <= nr < rows and 0 <= nc < cols and
maze[nr][nc] != '1' and (nr, nc) not in visited):
visited.add((nr, nc))
stack.append((nr, nc))
parent[(nr, nc)] = curr
return None
def print_maze(maze, path=None, title="Maze"):
"""Print the maze, optionally highlighting the path with '*'."""
print(f"\n{title}:")
temp_maze = [row[:] for row in maze]
if path:
for r, c in path:
temp_maze[r][c] = '*'
for row in temp_maze:
print(' '.join(row))
# Example maze:
# S 0 0 1 0
# 1 1 0 0 0
# 0 0 0 1 E
maze = [
['S', '0', '0', '1', '0'],
['1', '1', '0', '0', '0'],
['0', '0', '0', '1', 'E']
]
# Solve and display
print_maze(maze, title="Original Maze")
path_bfs = solve_bfs(maze)
if path_bfs:
print(f"BFS path length: {len(path_bfs) - 1}")
print_maze(maze, path_bfs, "Solved with BFS (shortest path)")
else:
print("No path found with BFS")
path_dfs = solve_dfs(maze)
if path_dfs:
print(f"DFS path length: {len(path_dfs) - 1}")
print_maze(maze, path_dfs, "Solved with DFS (one possible path)")
else:
print("No path found with DFS")
# To use with custom maze:
# Replace the 'maze' list above with your own 2D list of strings.
# Maze format:
# - '0': open path
# - '1': wall
# - 'S': start (exactly one)
# - 'E': end (exactly one)
# All cells treated as valid paths except '1'.
How to Use
- Run the program: It uses a hardcoded example maze and prints:
- Original maze.
- BFS solution (shortest path marked with
*).
- DFS solution (a path marked with
*).
- Custom mazes: Replace the
maze list. Ensure rectangular grid, one 'S', one 'E'.
- Maze rules: Moves up/down/left/right. No diagonals. 'S', 'E', '0' are traversable.
- Output example (for the given maze):
Original Maze:
S 0 0 1 0
1 1 0 0 0
0 0 0 1 E
BFS path length: 6
Solved with BFS (shortest path):
* 0 0 1 0
1 1 * 0 0
0 0 * 1 E
* * * * *
DFS path length: 8
Solved with DFS (one possible path):
* 0 0 1 *
1 1 0 0 *
0 0 * 1 E
(Path varies based on direction order)
BFS always finds the shortest path; DFS finds one path (length may vary). Both use O(rows * cols) time/space.