Skip to content

Commit 4bc9b9b

Browse files
authored
Create shortest-path-in-binary-matrix.cpp
1 parent e92ee9f commit 4bc9b9b

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Time: O(n^2)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
7+
static const vector<pair<int, int>> directions = {{-1, -1}, {-1, 0}, {-1, 1},
8+
{ 0, -1}, { 0, 1},
9+
{ 1, -1}, { 1, 0}, { 1, 1}};
10+
int result = 0;
11+
queue<pair<int, int>> q({{0, 0}});
12+
while (!q.empty()) {
13+
++result;
14+
queue<pair<int, int>> next_depth;
15+
while (!q.empty()) {
16+
int i, j;
17+
tie(i, j) = q.front(); q.pop();
18+
if (0 <= i && i < grid.size() &&
19+
0 <= j && j < grid[0].size() &&
20+
!grid[i][j]) {
21+
grid[i][j] = 1;
22+
if (i == grid.size() - 1 && j == grid.size() - 1) {
23+
return result;
24+
}
25+
for (const auto& dir : directions) {
26+
next_depth.emplace(i + dir.first, j + dir.second);
27+
}
28+
}
29+
}
30+
q = move(next_depth);
31+
}
32+
return -1;
33+
}
34+
};

0 commit comments

Comments
 (0)