550. Shortest Path to Get Food
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the shortest path from a starting cell '*' to any food cell '#' in a 2D grid. The grid contains free spaces 'O' we can travel through and obstacles 'X' we cannot. We can move in four directions (north, east, south, west). This is a classic shortest path problem on an unweighted graph. The grid cells can be seen as nodes in a graph, and adjacent, non-obstacle cells have an edge of weight 1 between them. Breadth-First Search (BFS) is the ideal algorithm for finding the shortest path in an unweighted graph from a single source to a target.
Solution
Shortest Path to Get Food in Python
from collections import deque
class Solution:
def getFood(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
# Find the starting position '*'
start_pos = None
for r in range(m):
for c in range(n):
if grid[r][c] == '*':
start_pos = (r, c)
break
if start_pos:
break
# BFS queue storing (row, col, distance)
queue = deque([(start_pos[0], start_pos[1], 0)])
# Visited set to prevent cycles
visited = {start_pos}
# Directions for moving up, down, left, right
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
while queue:
r, c, dist = queue.popleft()
# Explore neighbors
for dr, dc in directions:
nr, nc = r + dr, c + dc
# Check boundaries and if the cell is valid to visit
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] != 'X' and (nr, nc) not in visited:
# If food is found, return the path length
if grid[nr][nc] == '#':
return dist + 1
# Mark as visited and add to the queue
visited.add((nr, nc))
queue.append((nr, nc, dist + 1))
# If the queue becomes empty and no food is found
return -1
Shortest Path to Get Food in Java
class Solution {
public int getFood(char[][] grid) {
int m = grid.length;
int n = grid[0].length;
// Find the starting position '*'
int startRow = -1, startCol = -1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '*') {
startRow = i;
startCol = j;
break;
}
}
if (startRow != -1) break;
}
// BFS queue storing {row, col, distance}
Queue<int[]> queue = new ArrayDeque<>();
queue.offer(new int[]{startRow, startCol, 0});
// Visited array to prevent cycles
boolean[][] visited = new boolean[m][n];
visited[startRow][startCol] = true;
// Directions for moving up, down, left, right
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!queue.isEmpty()) {
int[] current = queue.poll();
int r = current[0];
int c = current[1];
int dist = current[2];
// Explore neighbors
for (int[] dir : dirs) {
int nr = r + dir[0];
int nc = c + dir[1];
// Check boundaries and if the cell is valid to visit
if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] != 'X' && !visited[nr][nc]) {
// If food is found, return the path length
if (grid[nr][nc] == '#') {
return dist + 1;
}
// Mark as visited and add to the queue
visited[nr][nc] = true;
queue.offer(new int[]{nr, nc, dist + 1});
}
}
}
// If the queue becomes empty and no food is found
return -1;
}
}
Shortest Path to Get Food in C++
class Solution {
public:
int getFood(vector<vector<char>>& grid) {
int m = grid.size();
int n = grid[0].size();
// Find the starting position
int startRow = -1, startCol = -1;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '*') {
startRow = i;
startCol = j;
break;
}
}
if (startRow != -1) break;
}
// BFS queue storing {row, col, distance}
queue<tuple<int, int, int>> q;
q.push({startRow, startCol, 0});
// Visited set to prevent cycles
vector<vector<bool>> visited(m, vector<bool>(n, false));
visited[startRow][startCol] = true;
// Directions for moving up, down, left, right
int dr[] = {-1, 1, 0, 0};
int dc[] = {0, 0, -1, 1};
while (!q.empty()) {
auto [r, c, dist] = q.front();
q.pop();
// Explore neighbors
for (int i = 0; i < 4; ++i) {
int nr = r + dr[i];
int nc = c + dc[i];
// Check boundaries and if the cell is valid to visit
if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] != 'X' && !visited[nr][nc]) {
// If food is found, return the path length
if (grid[nr][nc] == '#') {
return dist + 1;
}
// Mark as visited and add to the queue
visited[nr][nc] = true;
q.push({nr, nc, dist + 1});
}
}
}
// If the queue becomes empty and no food is found
return -1;
}
};
Shortest Path to Get Food in TypeScript
function getFood(grid: string[][]): number {
const m = grid.length;
const n = grid[0].length;
// Find the starting position '*'
let startRow = -1, startCol = -1;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === '*') {
startRow = i;
startCol = j;
break;
}
}
if (startRow !== -1) break;
}
// BFS queue storing [row, col, distance]
const queue: [number, number, number][] = [[startRow, startCol, 0]];
// Visited set to prevent cycles. Using a string key "row,col".
const visited = new Set<string>();
visited.add(`${startRow},${startCol}`);
// Directions for moving up, down, left, right
const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];
while (queue.length > 0) {
const [r, c, dist] = queue.shift()!;
// Explore neighbors
for (const [dr, dc] of dirs) {
const nr = r + dr;
const nc = c + dc;
const key = `${nr},${nc}`;
// Check boundaries and if the cell is valid to visit
if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] !== 'X' && !visited.has(key)) {
// If food is found, return the path length
if (grid[nr][nc] === '#') {
return dist + 1;
}
// Mark as visited and add to the queue
visited.add(key);
queue.push([nr, nc, dist + 1]);
}
}
}
// If the queue becomes empty and no food is found
return -1;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.