You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any 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.

You can travel to any adjacent cell north, east, south, or west of your current location if there is not an obstacle.

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.

Idea

BFS and track visited

class Solution:
    def getFood(self, grid: List[List[str]]) -> int:
        N = len(grid)
        M = len(grid[0])
        visited = [[False] * M for _ in range(N)]
        nodes = deque([next((i,j) for i in range(N) for j in range(M) if grid[i][j] == '*')])
        
        steps = 0
        while nodes:
            steps += 1
            for i in range(len(nodes)):
                n = nodes.popleft()
                for dx,dy in [
                        (n[0]-1,n[1]), 
                        (n[0]+1, n[1]),
                        (n[0], n[1]-1),
                        (n[0], n[1]+1)]:
                    if dx < 0 or dx >= N or dy < 0 or dy >= M or visited[dx][dy]:
                        continue
                    val = grid[dx][dy]
                    visited[dx][dy] = True
                    if val == '#':
                        return steps
                    if val == 'O':
                        nodes.append((dx, dy))
        return -1