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
利用 即可。只不过这次的 有 个方向。另外一点就是,我们可以直接在 上面进行修改:修改为路径长度,当然判断的条件为:
- 没有被访问:
- 符合边界条件
点击查看代码
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; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】