广搜模版
2025-08-14 21:09:54
发布于:浙江
1阅读
0回复
0点赞
因为广搜是天然可以求无权图的最短路径的,所以直接模版:
#include <bits/stdc++.h>
using namespace std;
int sz[10][10],vis[10][10],_x[]={0,1,0,-1},_y[]={1,0,-1,0};
struct m{
int x,y,flag;
}l,r;
queue<m> a;
//判断函数
bool check(m l){
return (l.x>=1 and l.y<=5 and l.x<=5 and l.y>=1 and vis[l.x][l.y]==0 and sz[l.x][l.y]==0);
}
//广搜
void bfs(int x,int y){
vis[x][y]=1;
a.push({x,y,0});
while(a.size()){
r=a.front();
a.pop();
if(r.x==r.y and r.x==5){
cout << r.flag;
return ;
}
for(int i=0;i<4;i++){
l.x=r.x+_x[i];
l.y=r.y+_y[i];
l.flag=r.flag+1;
if(check(l)){
vis[l.x][l.y]=1;
a.push(l);
}
}
}cout << "-1";
}
//输入
void solve(){
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
cin >> sz[i][j];
}
}bfs(1,1);
}
int main(){
solve();
return 0;
}
这里空空如也
有帮助,赞一个