[Geeks for Geeks] Shortest Path by Removing K walls

Shortest Path by Removing K walls

Given a 2-D binary matrix of size n*m, where 0 represents an empty space while 1 represents a wall you cannot walk through. You are also given an integer k.
You can walk up, down, left, or right. Given that you can remove up to k walls, return the minimum number of steps to walk from the top left corner (0, 0) to the bottom right corner (n-1, m-1).

Note: If there is no way to walk from the top left corner to the bottom right corner, return -1.

  • Time : O(nmk)
  • Space : O(nmk)
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
36
37
38
39
class Solution {
bool vis[51][51][51*51];

public:
int shotestPath(vector<vector<int>> mat, int n, int m, int k) {
if(n == 1 and m == 1) return 0;
memset(vis, false, sizeof vis);
queue<array<int,3>> q;
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
q.push({0,0,k});
vis[0][0][k] = true;
int res = 1;

while(!q.empty()) {
int sz = q.size();
while(sz--) {
auto A = q.front(); q.pop();
auto y = A[0], x = A[1], b = A[2];
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) {
if(mat[ny][nx] == 0 and !vis[ny][nx][b]) {
if(ny == n - 1 and nx == m - 1) return res;
vis[ny][nx][b] = true;
q.push({ny,nx,b});
} else if(mat[ny][nx] == 1 and b and !vis[ny][nx][b-1]) {
if(ny == n - 1 and nx == m - 1) return res;
vis[ny][nx][b-1] = true;
q.push({ny,nx,b-1});
}
}
}
}
res++;
}

return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/18/PS/GeeksforGeeks/shortest-path-by-removing-k-walls/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.