Shortest Path to Get Food Problem
Description
LeetCode Problem 1730.
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.
Example 1:

Input: grid = [["X","X","X","X","X","X"],["X","*","O","O","O","X"],["X","O","O","#","O","X"],["X","X","X","X","X","X"]]
Output: 3
Explanation: It takes 3 steps to reach the food.
Example 2:

Input: grid = [["X","X","X","X","X"],["X","*","X","O","X"],["X","O","X","#","X"],["X","X","X","X","X"]]
Output: -1
Explanation: It is not possible to reach the food.
Example 3:

Input: grid = [["X","X","X","X","X","X","X","X"],["X","*","O","X","O","#","O","X"],["X","O","O","X","O","O","X","X"],["X","O","O","O","O","#","O","X"],["X","X","X","X","X","X","X","X"]]
Output: 6
Explanation: There can be multiple food cells. It only takes 6 steps to reach the bottom food.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 200grid[row][col]is'*','X','O', or'#'.- The
gridcontains exactly one'*'.
Solution
Approach: BFS (Breadth-First Search)
Find the start cell * and run a breadth-first search from it over the open cells (O) and food cells (#), moving up, down, left and right and never entering X. The first time a # is reached, the number of layers walked so far is the shortest distance. If the queue empties first, return -1.
Complexity: O(mn) time and O(mn) space, where m and n are the grid dimensions.
from collections import deque
class Solution:
def getFood(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
i, j = next((i, j) for i in range(m) for j in range(n) if grid[i][j] == '*')
q = deque([(i, j)])
dirs = (-1, 0, 1, 0, -1)
ans = 0
while q:
ans += 1
for _ in range(len(q)):
i, j = q.popleft()
for a, b in zip(dirs, dirs[1:]):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n:
if grid[x][y] == '#':
return ans
if grid[x][y] == 'O':
grid[x][y] = 'X'
q.append((x, y))
return -1