To find the shortest path in a maze (2D grid) from a start point to an exit, the most effective algorithm to use is Breadth-First Search (BFS).
✅ Why BFS?
- BFS guarantees the shortest path in an unweighted grid (which a maze can be considered as—each move costs the same).
- It searches level by level, ensuring the first time we reach the destination, it's via the shortest path.
🔧 Problem Setup
- A maze is given as a 2D grid.
0 represents a wall (blocked cell).
1 represents an open path.
- You can move up, down, left, and right — no diagonals.
- Start and exit are given as
(row, col) coordinates.
🧠 Algorithm (BFS):
- Use a queue to track current positions and the steps taken so far.
- Use a set or a visited matrix to avoid revisiting cells.
- For each position dequeued, check if it's the exit.
- Otherwise, enqueue its unvisited valid neighbors.
✅ Python Implementation
from collections import deque
def shortest_path_length(maze, start, end):
"""
Find the shortest path in a 2D maze from start to end using BFS.
:param maze: List[List[int]] - 2D grid where 1 = open path, 0 = wall
:param start: Tuple[int, int] - starting coordinate (row, col)
:param end: Tuple[int, int] - destination coordinate (row, col)
:return: int - length of the shortest path, or -1 if no path exists
"""
if not maze or not maze[0]:
return -1 # invalid maze
rows, cols = len(maze), len(maze[0])
sr, sc = start
er, ec = end
if maze[sr][sc] == 0 or maze[er][ec] == 0:
return -1 # start or end is a wall
# Directions: up, down, left, right
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
# Queue: (row, col, steps)
queue = deque()
queue.append((sr, sc, 0))
visited = [[False for _ in range(cols)] for _ in range(rows)]
visited[sr][sc] = True
while queue:
r, c, steps = queue.popleft()
# Check if we've reached the destination
if (r, c) == (er, ec):
return steps
# Explore neighbors
for dr, dc in directions:
nr, nc = r + dr, c + dc
# Valid and unvisited
if 0 <= nr < rows and 0 <= nc < cols and \
maze[nr][nc] == 1 and not visited[nr][nc]:
visited[nr][nc] = True
queue.append((nr, nc, steps + 1))
# If we reach here, no path exists
return -1
📌 Example Usage
maze = [
[1, 0, 1, 1],
[1, 1, 1, 0],
[0, 1, 0, 1],
[1, 1, 1, 1],
]
start = (0, 0)
exit = (3, 3)
print(shortest_path_length(maze, start, exit)) # Output: shortest path length or -1
🧪 Example Walkthrough
Maze:
1 0 1 1
1 1 1 0
0 1 0 1
1 1 1 1
Start at (0, 0), goal is (3, 3)
- Shortest path is:
(0,0) → (1,0) → (1,1) → (1,2) → (2,1) → (3,1) → (3,2) → (3,3) – Total 7 steps
📈 Time & Space Complexity
- Time Complexity: O(N × M), where N = rows, M = columns.
- Space Complexity: O(N × M) for the
visited matrix and queue in the worst-case (maze fully open).
🚫 Optional Enhancements
- Return the actual path (not just length): you can maintain a parent map and trace back.
- Add diagonal moves if allowed.
- Or use A* (A-star) if you want faster heuristically-based pathfinding.
✅ Summary
Use BFS for shortest paths in mazes:
- Works great in grid-based pathfinding with uniform weights.
- Provides guaranteed optimal path length.
- Fast enough for most real-time puzzles.
Let me know if you want to retrieve the actual path, not just its length!