#1730
Medium Algorithms Shortest path to get food
Array Breadth-First Search Matrix
57.2% acceptance
Mar 31, 2026
722
41
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.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn get_food(grid: Vec<Vec<char>>) -> i32 {
let m = grid.len();
let n = grid[0].len();
let mut queue = std::collections::VecDeque::new();
let mut visited = vec![vec![false; n]; m];
for i in 0..m {
for j in 0..n {
if grid[i][j] == '*' {
queue.push_back((i, j, 0));
visited[i][j] = true;
break;
}
}
if !queue.is_empty() { break; }
}
while let Some((r, c, dist)) = queue.pop_front() {
for (dr, dc) in [(!0usize, 0), (1, 0), (0, !0usize), (0, 1)] {
let nr = r.wrapping_add(dr);
let nc = c.wrapping_add(dc);
if nr < m && nc < n && !visited[nr][nc] && grid[nr][nc] != 'X' {
if grid[nr][nc] == '#' { return dist + 1; }
visited[nr][nc] = true;
queue.push_back((nr, nc, dist + 1));
}
}
}
-1
}
}