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
*OO#OXOO0123BFS explores in expanding waves - first food found = shortest pathAnswer: 3 steps to reach food
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

n
2n
โœ“ Linear Growth
Space Complexity
O(mร—n)

Queue and visited set can store up to all cells in worst case

n
2n
โšก 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
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 19
47.2K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen