forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortest-path-in-binary-matrix.cpp
34 lines (33 loc) · 1.18 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
// Time: O(n^2)
// Space: O(n)
class Solution {
public:
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
static const vector<pair<int, int>> directions = {{-1, -1}, {-1, 0}, {-1, 1},
{ 0, -1}, { 0, 1},
{ 1, -1}, { 1, 0}, { 1, 1}};
int result = 0;
queue<pair<int, int>> q({{0, 0}});
while (!q.empty()) {
++result;
queue<pair<int, int>> next_depth;
while (!q.empty()) {
int i, j;
tie(i, j) = q.front(); q.pop();
if (0 <= i && i < grid.size() &&
0 <= j && j < grid[0].size() &&
!grid[i][j]) {
grid[i][j] = 1;
if (i == grid.size() - 1 && j == grid.size() - 1) {
return result;
}
for (const auto& dir : directions) {
next_depth.emplace(i + dir.first, j + dir.second);
}
}
}
q = move(next_depth);
}
return -1;
}
};