LeetCode 1091 Shortest Path in Binary Matrix
Given an n x n
binary matrix grid
, return the length of the shortest clear path in the matrix. If there is no clear path, return -1
.
A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)
) to the bottom-right cell (i.e., (n - 1, n - 1)
) such that:
- All the visited cells of the path are 0.
- All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).
The length of a clear path is the number of visited cells of this path.
Solution
利用 \(BFS\) 即可。只不过这次的 \(dir\) 有 \(8\) 个方向。另外一点就是,我们可以直接在 \(grid\) 上面进行修改:修改为路径长度,当然判断的条件为:
- 没有被访问: \(grid[i][j]=0\)
- 符合边界条件
点击查看代码
class Solution {
private:
int ans = -1;
queue<vector<int>> q;
int dir[8][2] = {
-1,0,
0,-1,
1,0,
0,1,
-1,-1,
1,-1,
1,1,
-1,1
};
bool check(int i,int j,int r, int c){
if(i<0||j<0||i>=r||j>=c)return false;
return true;
}
public:
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
int r = grid.size(), c = grid[0].size();
if(grid[0][0])return -1;
grid[0][0]=1;
q.push({0,0});
while(!q.empty()){
auto f = q.front();q.pop();
int x = f[0], y = f[1];
if(x==r-1 && y==c-1)return grid[x][y];
for(int i=0;i<8;i++){
int nx = x+dir[i][0], ny = y+dir[i][1];
if(check(nx,ny,r,c) && grid[nx][ny]==0){
grid[nx][ny] = grid[x][y]+1;
q.push({nx,ny});
}
}
}
return -1;
}
};