Problem
You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall. Each False boolean represents a tile you can walk on.
Given this matrix, a start coordinate, and an end coordinate, return the minimum number of steps required to reach the end coordinate from the start. If there is no possible path, then return null. You can move up, left, down, and right. You cannot move through walls. You cannot wrap around the edges of the board.
Examples
Example 1: $$ board = \begin{bmatrix} \colorbox{green} f & \colorbox{green} f & \colorbox{green} f & \colorbox{green} f \\ \colorbox{red} t & \colorbox{red} t & \colorbox{green} f & \colorbox{red} t \\ \colorbox{green} f & \colorbox{green} f & \colorbox{green} f & \colorbox{green} f \\ \colorbox{green} f & \colorbox{green} f & \colorbox{green} f & \colorbox{green} f \end{bmatrix} \Longrightarrow path = \begin{bmatrix} \colorbox{blue} f & \colorbox{blue} f & \colorbox{blue} f & \colorbox{green} f \\ \colorbox{red} t & \colorbox{red} t & \colorbox{blue} f & \colorbox{red} t \\ \colorbox{blue} f & \colorbox{blue} f & \colorbox{blue} f & \colorbox{green} f \\ \colorbox{blue} f & \colorbox{green} f & \colorbox{green} f & \colorbox{green} f \end{bmatrix} $$
|
|
and start = (3, 0)
(bottom left) and end = (0, 0)
(top left), the minimum number of steps required to reach the end is 7, since we would need to go through (1, 2)
because there is a wall everywhere else on the second row.
Similar Problem
Shortest Path in Binary Matrix
Solution
Method 1 - Shortest Path BFS
shortest_path
function takes the maze, start coordinates, and end coordinates as input.- It defines directions for movement (up, right, down, left) and initializes a
visited
matrix to track explored cells. - A queue using
deque
is used for BFS. It stores tuples of (current coordinate, steps taken). - The algorithm starts at the
start
coordinate and marks it as visited. - It iterates through the queue, exploring neighbors (up, right, down, left) of the current cell.
- For each neighbor, it checks if it’s within bounds, not visited, and not a wall.
- If these conditions are met, the neighbor is added to the queue with the updated step count (
steps + 1
). - The process repeats until the queue is empty or the
end
coordinate is found. - If the
end
coordinate is found, the function returns the number of steps taken (shortest path). - If the queue becomes empty without finding the
end
, it means there’s no path, and the function returnsNone
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m*n)
wherem
is number of rows andn
is number of columns - 🧺 Space complexity:
O(m*n)
for usingvisited
matrix