forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1091.cpp
More file actions
46 lines (34 loc) · 1.23 KB
/
1091.cpp
File metadata and controls
46 lines (34 loc) · 1.23 KB
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
class Solution {
public:
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
if(grid[0][0] || grid.back().back())
return -1;
int start = 1, ans = 2;
int xMax = grid[0].size() - 1;
int yMax = grid.size() - 1;
if(!xMax && !yMax)
return 1 - (grid[0][0] << 1);
grid[0][0] = -1;
queue<pair<int, int>> q;
q.push({0, 0});
while(start){
while(start--){
auto[x, y] = q.front();
q.pop();
for(int i = max(x - 1, 0), currX = min(x + 1, xMax); i <= currX; i++){
for(int j = max(y - 1, 0), currY = min(y + 1, yMax); j <= currY; j++){
if(i == xMax && j == yMax)
return ans;
if(!grid[j][i]){
grid[j][i] = -1;
q.push({i, j});
}
}
}
}
ans++;
start = q.size();
}
return -1;
}
};