Shortest Path to Get Food - Problem
You're trapped in a maze and starving! You need to find the shortest path to reach any food source as quickly as possible.
Given an m ร n character matrix representing a grid-based world:
'*'- Your starting location (exactly one exists)'#'- Food cells (one or more may exist)'O'- Free walkable space'X'- Obstacles that block movement
You can move in four directions (north, east, south, west) to adjacent cells, but cannot pass through obstacles.
Goal: Return the minimum number of steps to reach any food cell, or -1 if no path exists.
Example: If you're at position (0,0) marked with '*' and there's food '#' at position (2,2), you need to find the shortest route avoiding any 'X' obstacles.
Input & Output
example_1.py โ Basic Path
$
Input:
grid = [['*','O','#'],['O','O','X'],['O','X','X']]
โบ
Output:
2
๐ก Note:
Starting at (0,0), we can reach food at (0,2) in 2 steps: right to (0,1), then right to (0,2).
example_2.py โ Multiple Food Sources
$
Input:
grid = [['*','O','O','O'],['O','X','O','#'],['O','O','O','#'],['O','#','X','X']]
โบ
Output:
3
๐ก Note:
Multiple food cells exist. The closest one at (1,3) can be reached in 3 steps, which is shorter than reaching other food cells.
example_3.py โ No Path Available
$
Input:
grid = [['*','X','X'],['X','X','X'],['X','X','#']]
โบ
Output:
-1
๐ก Note:
Player is completely surrounded by obstacles 'X', making it impossible to reach any food cell.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start BFS from player position '*' with distance 0
2
Wave 1
Explore all adjacent cells (distance 1) and add valid ones to queue
3
Wave 2
Process distance 1 cells, explore their neighbors (distance 2)
4
Continue
Keep expanding waves until food '#' is found or no cells remain
Key Takeaway
๐ฏ Key Insight: BFS explores positions in order of increasing distance, so the first food cell encountered is guaranteed to be at the shortest possible distance.
Time & Space Complexity
Time Complexity
O(mรn)
We visit each cell at most once, where mรn is the total number of cells
โ Linear Growth
Space Complexity
O(mรn)
Queue and visited set can store up to all cells in worst case
โก Linearithmic Space
Constraints
- m == grid.length
- n == grid[i].length
- 1 โค m, n โค 200
- grid[i][j] is '*', '#', 'O', or 'X'
- Exactly one '*' cell exists
- At least one '#' cell exists
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code