-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsolution.cpp
43 lines (36 loc) · 1.26 KB
/
solution.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
35
36
37
38
39
40
41
42
43
class Solution {
public:
int shortestPathBinaryMatrix(std::vector<std::vector<int>>& grid) {
int n = grid.size();
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) {
return -1;
}
std::queue<std::vector<int>> queue;
queue.push({0, 0, 1});
grid[0][0] = 1;
std::vector<std::vector<int>> directions = {
{-1, -1}, {-1, 0}, {-1, 1},
{0, -1}, {0, 1},
{1, -1}, {1, 0}, {1, 1}
};
while (!queue.empty()) {
auto current = queue.front();
queue.pop();
int row = current[0];
int col = current[1];
int distance = current[2];
if (row == n - 1 && col == n - 1) {
return distance;
}
for (const auto& direction : directions) {
int newRow = row + direction[0];
int newCol = col + direction[1];
if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < n && grid[newRow][newCol] == 0) {
grid[newRow][newCol] = 1;
queue.push({newRow, newCol, distance + 1});
}
}
}
return -1;
}
};