1730. Shortest Path To Get Food
You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at a 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.
Return the length of the shortest path for you to reach any food cell. If there is no path for you to reach food, return -1.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Notes
Intuition
Finding the shortest path in an unweighted grid is a classic BFS problem. BFS explores all cells at distance k before any cell at distance k+1, guaranteeing the first food cell reached is the closest.
Implementation
First, locate the starting position (*). Initialize a queue with the start coordinate and path length 0, plus a visited set. Process cells level by level: for each cell, check its four neighbors. Skip if visited or blocked (X). If it's food (#), return the current path length + 1. Otherwise, add to visited and queue with incremented path.
Edge-cases
If BFS completes without finding food, return -1 (no reachable food). The visited set prevents revisiting cells and infinite loops.
- Time: O(m * n) — each cell visited at most once
- Space: O(m * n) — visited set and queue