Skip to content

Commit bcbf3d9

Browse files
author
Kowsihan-sk
committed
added shortest path in binary matrix problem
1 parent 6eba01e commit bcbf3d9

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public:
3+
4+
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
5+
int n = grid.size(), len = 1;
6+
if(grid[0][0] == 1 || grid[n-1][n-1] == 1) return -1;
7+
if(n==1) return 1;
8+
9+
vector<vector<int>> off = {{0,1},{0,-1},{1,0},{-1,0},{1,1},{-1,-1},{1,-1},{-1,1}};
10+
queue<pair<int,int>> q;
11+
q.push({0,0});
12+
grid[0][0] = 1;
13+
14+
int sz, row, col, i, j;
15+
16+
while(!q.empty()){
17+
sz = q.size();
18+
for(i = 0; i < sz; i++){
19+
row = q.front().first, col = q.front().second;
20+
q.pop();
21+
22+
if(row == n-1 && col == n-1) return len;
23+
24+
for(j = 0; j < 8; j++){
25+
int x = row + off[j][0], y = col + off[j][1];
26+
if(x >= 0 && y >= 0 && x < n && y < n && grid[x][y] == 0){
27+
grid[x][y] = 1;
28+
q.push({x,y});
29+
}
30+
}
31+
32+
}
33+
len++;
34+
}
35+
36+
return -1;
37+
}
38+
};

0 commit comments

Comments
 (0)