BFS代码
2025-05-04 16:41:24
发布于:上海
3阅读
0回复
0点赞
代码如下:
#include<bits/stdc++.h>
using namespace std;
int n,m,b[110][110],stx,sty,edx,edy;
char mp[110][110];
int dx[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
struct node{
int x,y,step;
}l,r;
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]=='S'){
stx=i,sty=j;
}
if(mp[i][j]=='T'){
edx=i,edy=j;
}
}
}
queue<node>q;
q.push({stx,sty,0});
b[stx][sty]=1;
while(q.size()){
r=q.front();
q.pop();
if(r.x==edx && r.y==edy){
cout<<r.step;
return 0;
}
for(int i=0;i<4;i++){
l.x=r.x+dx[i][0];
l.y=r.y+dx[i][1];
l.step=r.step+1;
if(l.x>=1 && l.x<=n && l.y>=1 && l.y<=m && b[l.x][l.y]!=1 && mp[l.x][l.y]!='#'){
b[l.x][l.y]=1;
q.push(l);
}
}
}
cout<<-1;
return 0;
}
其实我是用AI写的,信吗
这里空空如也
有帮助,赞一个