xinyu04

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

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 即可。只不过这次的 dir8 个方向。另外一点就是,我们可以直接在 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;
}
};

posted on   Blackzxy  阅读(21)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示