Shortest Path to Get Food - Problem

You are starving and want to eat food as quickly as possible. Find the shortest path to arrive at any food cell.

You are given an m x n character matrix grid with these cell types:

  • '*' is your location (exactly one cell)
  • '#' is a food cell (may be multiple)
  • 'O' is free space you can travel through
  • 'X' is an obstacle you cannot travel through

You can move to any adjacent cell (north, east, south, west) if it's not an obstacle.

Return the length of the shortest path to reach any food cell. If no path exists, return -1.

Input & Output

Example 1 — Basic Path
$ Input: grid = [["*","O","#"],["O","X","O"],["O","O","O"]]
Output: 2
💡 Note: Shortest path from '*' at (0,0) to '#' at (0,2): right → right = 2 steps
Example 2 — Blocked Direct Path
$ Input: grid = [["*","X","O"],["O","O","#"],["O","O","O"]]
Output: 4
💡 Note: Direct path blocked by 'X', must go: down → right → right → up = 4 steps
Example 3 — No Path
$ Input: grid = [["*","X"],["X","#"]]
Output: -1
💡 Note: Starting position completely surrounded by obstacles, no path to food

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 200
  • grid[i][j] is '*', '#', 'O', or 'X'
  • The grid contains exactly one '*'.

Visualization

Tap to expand
Shortest Path to Get Food ProblemInput Grid*O#OXOOOOBFS Exploration0121X-Shortest PathLegend:* Start# FoodO FreeX BlockedOutput: 2 steps
Understanding the Visualization
1
Input Grid
Matrix with start '*', food '#', free 'O', obstacles 'X'
2
BFS Search
Explore level by level to find shortest path
3
Path Length
Return steps to reach first food found
Key Takeaway
🎯 Key Insight: BFS guarantees shortest path because it explores all cells at distance k before any cell at distance k+1
Asked in
Facebook 15 Amazon 12 Google 8
28.5K Views
Medium Frequency
~25 min Avg. Time
847 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