题解BFS
2025-07-14 00:53:28
发布于:新疆
1阅读
0回复
0点赞
#include <iostream>
#include <queue>
using namespace std;
char mp[2005][2005];
bool vis[2005][2005];
int x1,y1;
struct node{
int x,y,step;
}l,r;
int n,m;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>mp[i][j];
if(mp[i][j]=='@'){
x1=i;
y1=j;
}
}
}
queue <node> que;
que.push({x1,y1,0});
vis[1][1]=1;
bool op=1;
while(que.size()){
r=que.front();
que.pop();
if(mp[r.x][r.y]=='*'){
cout<<r.step;
op=0;
break;
}
for(int i=0;i<4;i++){
l.x=r.x+dx[i];
l.y=r.y+dy[i];
l.step=r.step+1;
if(l.x<=n&&l.x>=1&&l.y<=m&&l.y>=1&&!vis[l.x][l.y]&&mp[l.x][l.y]!='#'){
vis[l.x][l.y]=1;
que.push(l);
}
}
}
if(op){
cout<<-1;
}
return 0;
}
这里空空如也
有帮助,赞一个