Shortest Path to Get Food — LeetCode 1730 Python Solution

MediumLeetCode PremiumBreadth-First SearchArrayMatrix
Problem
#1730
Reading time
4 min

The problem

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.

Example

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.

Python solution

Python
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 pairwise(dirs):
                    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

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(1) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1730. Shortest Path to Get Food is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1730. Shortest Path to Get Food?
LeetCode 1730. Shortest Path to Get Food is rated Medium on LeetCode.
What is the time complexity of LeetCode 1730. Shortest Path to Get Food?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 1730. Shortest Path to Get Food?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1730. Shortest Path to Get Food cover?
LeetCode 1730. Shortest Path to Get Food is tagged Breadth-First Search, Array and Matrix on LeetCode.
Is LeetCode 1730. Shortest Path to Get Food a premium problem?
Yes. LeetCode 1730. Shortest Path to Get Food is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview