[LeetCode] Shortest Path to Get Food

1730. Shortest Path to Get Food

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
int getFood(vector<vector<char>>& grid) {
int n = grid.size(), m = grid[0].size();
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
queue<pair<int,int>> q;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] == '*') {
q.push({i,j});
grid[i][j] = 'X';
}
}
}
int res = 1;
while(!q.empty()) {
int sz = q.size();
while(sz--) {
auto [y, x] = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and grid[ny][nx] != 'X') {
if(grid[ny][nx] == '#') return res;
grid[ny][nx] = 'X';
q.push({ny,nx});
}
}
}
res++;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/19/PS/LeetCode/shortest-path-to-get-food/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.