SDE & MLE Prep

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