Understanding the Problem
We are given a binary maze represented as a 2D grid, where each cell contains either a 1
(walkable) or a 0
(blocked). Our goal is to find the shortest path from a given source cell to a destination cell by moving only in four directions: up, down, left, or right. The movement is allowed only through cells containing 1
.
Think of each cell as a node in an unweighted graph, and the valid movements between walkable cells as edges. To find the shortest number of steps (i.e., the smallest number of edges), the most appropriate strategy is Breadth-First Search (BFS).
Step-by-Step Solution with Example
step 1: Initialize the distance grid
Create a 2D array dist
of the same size as the maze, initialized with Infinity
to represent that no cell has been visited yet. Set dist[source]
to 0
because that’s where we start.
step 2: Initialize the BFS queue
Use a queue to keep track of cells to explore. Each item in the queue contains the current cell’s coordinates and the distance taken to reach it. Initially, enqueue the source cell with distance 0
.
step 3: Process the queue
While the queue is not empty, do the following:
- Dequeue the front cell.
- Explore its four neighbors (up, down, left, right).
- For each neighbor, check if:
- It lies within the bounds of the maze.
- It is a walkable cell (value
1
).
- It has not been visited via a shorter path before.
- If all checks pass, update the neighbor’s distance and enqueue it.
step 4: Check for destination
If we reach the destination cell, we immediately return the current distance. This is guaranteed to be the shortest path because BFS explores all possible paths in increasing order of length.
step 5: If queue is exhausted
If the queue becomes empty without reaching the destination, return -1
to indicate that the destination is unreachable.
Example
Input:
maze = [
[1, 0, 1, 1],
[1, 1, 1, 0],
[0, 1, 0, 1],
[1, 1, 1, 1]
]
source = (0, 0)
destination = (3, 3)
Output: 7
Explanation:
The shortest path is:
(0,0) → (1,0) → (1,1) → (1,2) → (2,1) → (3,1) → (3,2) → (3,3)
which takes 7 steps.
Edge Cases
- Source or destination is blocked: If either the source or destination cell contains
0
, return -1
immediately.
- Source equals destination: If the source and destination are the same, return
0
because we are already there.
- Maze with all zeros: The function should handle this by returning
-1
.
- Disconnected components: Even if the maze is mostly walkable, ensure that there is a valid path from source to destination.
Finally
Breadth-First Search is ideal for this problem as it finds the shortest path in unweighted graphs like our binary maze. By using a queue and a distance array, we can ensure we explore the most efficient paths first. Always remember to check for edge cases to make your solution robust and reliable.
Comments
Loading comments...