1730. Shortest Path to Get Food
Problem
In the grid, '*' is your position (exactly one), '#' is food, 'O' is free space and 'X' is an obstacle. Moving up, down, left or right, return the length of the shortest path to any food cell, or −1 if none is reachable.
Example: ["XXXXXX","X*OOOX","XOO#OX","XXXXXX"] → 3
Constraints: up to 200 × 200.
Problem (Premium): a grid has exactly one '*' (you), any number of '#' (food), 'O' (free) and 'X' (wall). Moving up/down/left/right, return the length of the shortest path to any food cell, or −1.
Unweighted shortest path → BFS from '*', layer by layer; the first food cell reached is the answer.
Complexity: O(R·C).
class Solution:
def getFood(self, grid: List[List[str]]) -> int:
R, C = len(grid), len(grid[0])
start = next((r, c) for r in range(R) for c in range(C) if grid[r][c] == "*")
seen, q, steps = {start}, deque([start]), 0
while q:
steps += 1
for _ in range(len(q)):
r, c = q.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] != "X" and (nr, nc) not in seen:
if grid[nr][nc] == "#":
return steps
seen.add((nr, nc))
q.append((nr, nc))
return -1
G = lambda rows: [list(r) for r in rows]
assert Solution().getFood(G(["XXXXXX", "X*OOOX", "XOO#OX", "XXXXXX"])) == 3
assert Solution().getFood(G(["XXXXX", "X*XOX", "XOX#X", "XXXXX"])) == -1
assert Solution().getFood(G(["XXXXXXXX", "X*OXO#OX", "XOOXOOXX", "XOOOO#OX", "XXXXXXXX"])) == 6
assert Solution().getFood(G(["*#"])) == 1
class Solution {
public int getFood(char[][] grid) {
int R = grid.length, C = grid[0].length;
Deque<int[]> q = new ArrayDeque<>();
boolean[][] seen = new boolean[R][C];
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (grid[r][c] == '*') { q.add(new int[]{r, c}); seen[r][c] = true; }
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int steps = 1; !q.isEmpty(); steps++) {
for (int i = q.size(); i > 0; i--) {
int[] cur = q.poll();
for (int[] d : dirs) {
int r = cur[0] + d[0], c = cur[1] + d[1];
if (r < 0 || c < 0 || r >= R || c >= C || seen[r][c] || grid[r][c] == 'X') continue;
if (grid[r][c] == '#') return steps;
seen[r][c] = true;
q.add(new int[]{r, c});
}
}
}
return -1;
}
}
func getFood(grid [][]byte) int {
R, C := len(grid), len(grid[0])
var start [2]int
for r := 0; r < R; r++ {
for c := 0; c < C; c++ {
if grid[r][c] == '*' {
start = [2]int{r, c}
}
}
}
seen, q := map[[2]int]bool{start: true}, [][2]int{start}
for steps := 1; len(q) > 0; steps++ {
next := [][2]int{}
for _, p := range q {
for _, d := range [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {
nb := [2]int{p[0] + d[0], p[1] + d[1]}
if nb[0] < 0 || nb[0] >= R || nb[1] < 0 || nb[1] >= C || grid[nb[0]][nb[1]] == 'X' || seen[nb] {
continue
}
if grid[nb[0]][nb[1]] == '#' {
return steps
}
seen[nb] = true
next = append(next, nb)
}
}
q = next
}
return -1
}