-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
60 lines (56 loc) · 1.31 KB
/
solution.cpp
File metadata and controls
60 lines (56 loc) · 1.31 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//
// Created by mingyi on 23.04.20.
//
#include <vector>
#include <queue>
#include <cassert>
using namespace std;
int shortestPathBinaryMatrix(vector<vector<int>> &grid) {
int N = grid.size();
if (!N || grid[0][0] || grid[N - 1][N - 1]) {
return -1;
}
if (N == 1) {
return 1;
}
queue<pair<int, int>> q;
q.push({0, 0});
grid[0][0] = 1;
int pathLength = 1;
while (!q.empty()) {
pathLength++;
int qSize = q.size();
while (qSize--) {
pair<int, int> p = q.front();
q.pop();
int x0 = p.first;
int y0 = p.second;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (!i && !j) {
continue;
}
int x = x0 + i;
int y = y0 + j;
if (x == N - 1 && y == N - 1) {
return pathLength;
}
if (x >= 0 && y >= 0 && x < N && y < N && !grid[x][y]) {
grid[x][y] = 1;
q.push({x, y});
}
}
}
}
}
return -1;
}
int main() {
vector<vector<int>> grid1{{0, 1}, {1, 0}};
assert(2 == shortestPathBinaryMatrix(grid1));
vector<vector<int>> grid2{{0, 0, 0}, {1, 1, 0}, {1, 1, 0}};
assert(4 == shortestPathBinaryMatrix(grid2));
vector<vector<int>> grid3{{0}};
assert(1 == shortestPathBinaryMatrix(grid3));
return 0;
}