from collections import deque
def shortest_path_maze(maze: list[list[int]], start: tuple[int, int], exit: tuple[int, int]) -> int:
"""
Finds the length of the shortest path in a maze from start to exit.
Args:
maze: A 2D list representing the maze. 0 represents a path, 1 represents a wall.
start: A tuple representing the starting coordinates (row, col).
exit: A tuple representing the exit coordinates (row, col).
Returns:
The length of the shortest path, or -1 if no path exists.
"""
rows, cols = len(maze), len(maze[0])
queue = deque([(start[0], start[1], 0)]) # (row, col, distance)
visited = set()
visited.add(start)
# Possible movements (up, down, left, right)
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
while queue:
row, col, distance = queue.popleft()
if (row, col) == exit:
return distance
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
# Check if the new position is valid
if (0 <= new_row < rows and 0 <= new_col < cols and
maze[new_row][new_col] == 0 and (new_row, new_col) not in visited):
queue.append((new_row, new_col, distance + 1))
visited.add((new_row, new_col))
return -1 # No path found
# Example Usage:
if __name__ == "__main__":
maze = [
[0, 0, 0, 0],
[1, 1, 0, 1],
[0, 0, 0, 0],
[0, 1, 1, 0]
]
start = (0, 0)
exit = (3, 3)
shortest_path = shortest_path_maze(maze, start, exit)
if shortest_path != -1:
print(f"Shortest path length: {shortest_path}")
else:
print("No path found.")
maze2 = [
[0, 0, 0],
[1, 1, 1],
[0, 0, 0]
]
start2 = (0,0)
exit2 = (2,2)
shortest_path2 = shortest_path_maze(maze2, start2, exit2)
print(f"Shortest path length: {shortest_path2}") # Output: -1
Key improvements and explanations:
BFS (Breadth-First Search): Uses BFS, which guarantees finding the shortest path in an unweighted graph (like our maze).
deque for Queue: Uses collections.deque for efficient queue operations (append and popleft).
visited Set: Keeps track of visited cells to avoid cycles and redundant exploration. Using a set provides O(1) lookup for visited cells.
Clear Validity Checks: Explicitly checks if a new position is within the maze bounds, is a path (value 0), and hasn't been visited.
Directions: Uses a directions list to represent the possible movements (up, down, left, right), making the code more readable.
Distance Tracking: The queue stores the distance from the start to each cell, allowing us to return the correct path length when the exit is found.
Handles No Path: Returns -1 if no path is found.
Type Hints: Includes type hints for better readability and maintainability.
Example Usage: Provides a clear example of how to use the function.
Comments: Includes detailed comments to explain the code.
Handles edge cases: Correctly handles cases where no path exists.
Second test case: Added a second test case to demonstrate the no path found scenario.
Time and Space Complexity:
Time Complexity: O(R * C), where R is the number of rows and C is the number of columns in the maze. In the worst case, we might visit every cell in the maze.
Space Complexity: O(R * C) in the worst case, due to the visited set and the queue potentially storing all cells in the maze.