-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshortest-path-in-binary-matrix.cpp
60 lines (54 loc) · 1.68 KB
/
shortest-path-in-binary-matrix.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
class Solution {
public:
void updateQueue(queue<pair<int,int>> &q,vector<vector<int>>& grid,int x,int y){
int n = grid.size();
// cout<<"test";
if(x+1<n && x+1>=0 && grid[x+1][y]==0){
q.push({x+1,y});
}
if(y+1<n && y+1>=0 && grid[x][y+1]==0){
q.push({x,y+1});
}
if(x-1<n && x-1>=0 && grid[x-1][y]==0){
q.push({x-1,y});
}
if(y-1<n && y-1>=0 && grid[x][y-1]==0){
q.push({x,y-1});
}
if(x+1<n && x+1>=0 && y+1<n && y+1>=0 && grid[x+1][y+1]==0){
q.push({x+1,y+1});
}
if(x-1<n && x-1>=0 && y+1<n && y+1>=0 && grid[x-1][y+1]==0){
q.push({x-1,y+1});
}
if(x+1<n && x+1>=0 && y-1<n && y-1>=0 && grid[x+1][y-1]==0){
q.push({x+1,y-1});
}
if(x-1<n && x-1>=0 && y-1<n && y-1>=0 && grid[x-1][y-1]==0){
q.push({x-1,y-1});
}
}
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
queue<pair<int,int>> q;
int count=1;
q.push({0,0});
while(q.size()){
int s = q.size();
for(int i=0;i<s;i++){
auto cord = q.front();
int x = cord.first;
int y = cord.second;
q.pop();
if(grid[x][y]==1){
continue;
};
if(x==grid.size()-1 && y==grid.size()-1) return count;
cout<<x<<" "<<y<<" \n";
grid[x][y]=1;
updateQueue(q,grid,x,y);
}
count++;
}
return -1;
}
};