[LeetCode] Shortest Path in a Grid with Obstacles Elimination

1293. Shortest Path in a Grid with Obstacles Elimination

You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.

Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk 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
34
35
class Solution {
int visit[41][41][1601];
public:
int shortestPath(vector<vector<int>>& grid, int k) {
int n = grid.size(), m = grid[0].size();
if(n == 1 and m == 1) return 0;
int dx[4] = {0,1,0,-1}, dy[4] = {-1,0,1,0};
memset(visit, -1, sizeof(visit));
visit[0][0][k] = 0;
queue<vector<int>> q;
q.push({0,0,k});
while(!q.empty()) {
auto vec = q.front();
q.pop();

int cy = vec[0], cx = vec[1], ck = vec[2];
for(int i = 0; i < 4; i++) {
int nx = cx + dx[i], ny = cy + dy[i];
if(0 <= nx and nx < m and 0 <= ny and ny < n) {
if(grid[ny][nx] == 0 and visit[ny][nx][ck] == -1) {
q.push({ny,nx,ck});
visit[ny][nx][ck] = visit[cy][cx][ck] + 1;
if(ny == n - 1 and nx == m - 1) return visit[ny][nx][ck];
} else if(grid[ny][nx] == 1 and ck and visit[ny][nx][ck-1] == -1) {
q.push({ny,nx,ck-1});
visit[ny][nx][ck-1] = visit[cy][cx][ck] + 1;
if(ny == n - 1 and nx == m - 1) return visit[ny][nx][ck-1];
}
}
}
}

return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/02/PS/LeetCode/shortest-path-in-a-grid-with-obstacles-elimination/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.