-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1293ShortestCycle.cpp
62 lines (52 loc) · 2.03 KB
/
1293ShortestCycle.cpp
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include<bits/stdc++.h>
using namespace std;
// https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
// https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/712992/C%2B%2B-or-BFS
class Solution {
public:
int solve(vector<vector<int>>& grid,int k){
// At a particular cell we will store the number of obstacles that we can still remove after walking through that cell
vector<vector<int>> vis(grid.size(),vector<int>(grid[0].size(),-1));
queue<vector<int>> q;
// queue stores (x,y,current path length,number of obstacles we can still remove)
q.push({0,0,0,k});
while(!q.empty()){
auto t=q.front();
int x=t[0],y=t[1];
q.pop();
// Exit if current position is outside of the grid
if(x<0 || y<0 || x>=grid.size() || y>=grid[0].size()){
continue;
}
// Destination found
if(x==grid.size()-1 && y==grid[0].size()-1)
return t[2];
if(grid[x][y]==1){
if(t[3]>0) // If we encounter an obstacle and we can remove it
t[3]--;
else
continue;
}
// The cell was previously visited by some path and we were able to remove more obstacles from the previous path.
// Then we don't need to continue on our current path
if(vis[x][y]!=-1 && vis[x][y]>=t[3])
continue;
vis[x][y]=t[3];
q.push({x+1,y,t[2]+1,t[3]});
q.push({x,y+1,t[2]+1,t[3]});
q.push({x-1,y,t[2]+1,t[3]});
q.push({x,y-1,t[2]+1,t[3]});
}
return -1;
}
int shortestPath(vector<vector<int>>& grid, int k) {
return solve(grid,k);
}
};
int main(){
Solution ss;
vector<vector<int>> grid={{0,0,0},{1,1,0}, {0,0,0}, {0,1,1}, {0,0,0}};
int k=1;
ss.shortestPath(grid, k);
return 0;
}