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: 3
💡 Note: Direct path blocked by 'X', must go: down → right → right = 3 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 - BFS INPUT Character Grid (3x3) * START O # FOOD O X BLOCK O O O O Legend: * Start # Food O Free X Block grid = [["*","O","#"], ["O","X","O"], ["O","O","O"]] ALGORITHM STEPS 1 Initialize BFS Find start *, add to queue [(0,0,0)] 2 Process Level 0 Explore neighbors of * (0,1)=O [OK] | (1,0)=O [OK] Add both, distance = 1 3 Process Level 1 Check (0,1) neighbors (0,2) = # FOOD FOUND! Distance = 1 + 1 = 2 4 Return Result Shortest path = 2 steps Optimal Path: * --> O --> # (0,0) --> (0,1) --> (0,2) FINAL RESULT Grid with Shortest Path * O # O X O O O O Green border = Path taken Output: 2 OK - Shortest path found! 2 moves: right, right Key Insight: BFS guarantees the shortest path in an unweighted grid because it explores all cells at distance d before any cell at distance d+1. When we first reach any food cell, we've found the optimal path. Time Complexity: O(m*n) | Space Complexity: O(m*n) for the visited set and queue. TutorialsPoint - Shortest Path to Get Food | BFS Approach
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