Problem
You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell.
You are given an m x n
character matrix, grid
, of these different types of cells:
'*'
is your location. There is exactly one'*'
cell.'#'
is a food cell. There may be multiple food cells.'O'
is free space, and you can travel through these cells.'X'
is an obstacle, and you cannot travel through these cells.
You can travel to any adjacent cell north, east, south, or west of your current location if there is not an obstacle.
Return thelength of the shortest path for you to reach any food cell. If there is no path for you to reach food, return -1
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Example 4:
|
|
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
grid[row][col]
is'*'
,'X'
,'O'
, or'#'
.- The
grid
contains exactly one'*'
.
Solution
Method 1 – Breadth-First Search (BFS)
Intuition
Use BFS from the start cell to find the shortest path to any food cell. BFS guarantees the shortest path in an unweighted grid.
Approach
- Find the start cell (’*’).
- Use BFS to explore the grid, marking visited cells.
- Return the distance when a food cell (’#’) is reached, or -1 if not found.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(mn)
— Each cell is visited at most once. - 🧺 Space complexity:
O(mn)
— For the visited array and queue.