当前位置:网站首页>【宽度优先搜索】LeetCode1091二进制矩阵中的最短路径
【宽度优先搜索】LeetCode1091二进制矩阵中的最短路径
2022-06-10 06:45:00 【暮色_年华】
宽度优先搜索求迷宫最短路模板:

给你一个 n x n 的二进制矩阵 grid 中,返回矩阵中最短 畅通路径 的长度。如果不存在这样的路径,返回 -1 。
二进制矩阵中的 畅通路径 是一条从 左上角 单元格(即(0, 0))到 右下角 单元格(即(n - 1, n - 1))的路径,该路径同时满足下述要求:
路径途经的所有单元格都的值都是 0 。
路径中所有相邻的单元格应当在 8 个方向之一 上连通(即,相邻两单元之间彼此不同且共享一条边或者一个角)。
畅通路径的长度 是该路径途经的单元格总数。
每次有8种选择,套用bfs模板
#define x first
#define y second
typedef pair<int,int> PII;
class Solution {
public:
int shortestPathBinaryMatrix(vector<vector<int>>& g) {
if(g[0][0])return -1;
int n=g.size();
vector<vector<int>>dist(n,vector<int>(n,-1));
dist[0][0]=1;
queue<PII>q;
q.push({0,0});
int dx[]={-1,-1,-1,0,1,1,1,0};
int dy[]={-1,0,1,1,1,0,-1,-1};
while(q.size()){
auto t=q.front();
q.pop();
for(int i=0;i<8;i++){
int x=t.x+dx[i],y=t.y+dy[i];
if(x>=0&&x<n&&y>=0&&y<n&&g[x][y]==0&&dist[x][y]==-1){
dist[x][y]=dist[t.x][t.y]+1;
q.push({x,y});
}
}
}
return dist[n-1][n-1];
}
};边栏推荐
- Firefox browser settings point to proxy mode
- SQL practice: SQL solves problems in recent X days
- Go zero micro Service Practice Series (II. Service splitting)
- SQL practice: SQL optimization problems
- 告警消息何去何从?在飞书中飞起来
- Efficiency improvement: realize personal task management and monitoring with notation
- scala fastjson 获取jsonArray中 某个key的最大值
- Jacobo accurate to line collation
- Fastjson利用笔记
- Qt--- create dialog 2: quick dialog design
猜你喜欢

Oriental Star Hotel Management Catering project - query function

Wechat team sharing: how the wechat background does not crash under massive concurrent requests

QT---创建对话框2:快速对话框设计

One brush 163 force deduction hot topic-76 minimum covering substring (H)

Deploy MySQL based on statefulset in kubernetes (Part 1)

POC_Jenkins

Why can't lldb print view bounds? - Why can't LLDB print view. bounds?

tensorflow实验九----------泰坦尼克号

Nignx configuring websocket

Leetcode第 79 场双周赛-完成所有题目
随机推荐
Alibaba cloud OCR image recognition process
Model learning comprehension in Multi-Agent Reinforcement Learning Based on Model
Unlock TRPC high performance password: introduction to network scheme!
Nextcloud internal server error the server cannot complete your request workaround
scala fastjson 修改key或者value
电脑新加内存条后 游戏崩溃 浏览器卡死 电脑蓝屏
Fix a button in the lower right corner
Detailed explanation of C language linked list
Business topic: user usage path analysis
关于我并不是一个灰帽子的声明
彻底攻克 函数指针
在 Kubernetes 中基于 StatefulSet 部署 MySQL(下)
YoseZang 原创 特征码定位器 SignatureTest V6.36 Rls 发布
Teacher lihongyi's notes on machine learning -4.1 self attention
Proteus仿真p时出现Cannot open‘***\LISA5476.SDF’的错误
Teacher lihongyi's notes on machine learning -4.2 batch normalization
ROS2+Gazebo11+Car+OpenCV巡线识别和速度转向控制学习
How to solve mysql1045 and find the prompt is not an internal command
Unity fully elastic collision
SQL practice: SQL optimization problems