-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1091.shortest-path-in-binary-matrix.cpp
More file actions
39 lines (36 loc) · 1.14 KB
/
1091.shortest-path-in-binary-matrix.cpp
File metadata and controls
39 lines (36 loc) · 1.14 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
/*
* @lc app=leetcode id=1091 lang=cpp
*
* [1091] Shortest Path in Binary Matrix
*/
// @lc code=start
class Solution {
int move[8][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
public:
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
if(grid.front().front() || grid.back().back()) return -1;
int n = grid.size();
vector<vector<int>> dis(n, vector<int>(n));
dis[0][0] = 1;
queue<pair<int, int>> q;
q.push(make_pair(0, 0));
while(!q.empty()) {
auto [row, col] = q.front();
q.pop();
for(int i = 0; i < 8; ++i) {
int newRow = row + move[i][0];
int newCol = col + move[i][1];
if(newRow < 0 || newRow >= n || newCol < 0 || newCol >= n || grid[newRow][newCol]) continue;
if(dis[newRow][newCol]) continue;
dis[newRow][newCol] = dis[row][col] + 1;
q.push(make_pair(newRow, newCol));
}
}
return dis.back().back() ? dis.back().back() : -1;
}
};
// Accepted
// 89/89 cases passed (69 ms)
// Your runtime beats 79.27 % of cpp submissions
// Your memory usage beats 61.94 % of cpp submissions (20.9 MB)
// @lc code=end