Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1730: Shortest Path to Get Food

In this guide, we solve Leetcode #1730 Shortest Path to Get Food in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Breadth-First Search, Array, Matrix

Intuition

We need level-by-level exploration or shortest steps, which is ideal for BFS.

A queue naturally models the frontier of the search.

Approach

Push initial nodes into a queue and expand in layers.

Track visited nodes to prevent cycles.

Steps:

  • Initialize queue with start nodes.
  • Process level by level.
  • Track visited nodes.

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

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

The time complexity is O(m×n)O(m \times n)O(m×n), and the space complexity is O(1)O(1)O(1). The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy