题解
2024-11-08 21:51:41
发布于:江苏
14阅读
0回复
0点赞
#include<bits/stdc++.h>
using namespace std;
char a[105][105];
int sx,sy,zx,zy;
int dx[5]={0,0,1,0,-1};
int dy[5]={0,1,0,-1,0};
int c;
int n,m;
struct node{
int x,y,step;
}l,r;
void bfs(int x, int y){
queue<node>q;
q.push({x,y,0});
while(q.size()){
r=q.front();
q.pop();
if(r.x==zx&&r.y==zy){
cout<<r.step<<endl;
return;
}
for(int i=1;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)continue;
if(a[l.x][l.y]=='#')continue;
q.push(l);
a[l.x][l.y]='#';
}
}
cout<<-1<<endl;
}
int main(){
cin>>c;
while(c--){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
if(a[i][j]=='S'){
sx=i;
sy=j;
a[sx][sy]='#';
}else if(a[i][j]=='E'){
zx=i;
zy=j;
}
}
}
bfs(sx,sy);
}
return 0;
}
这里空空如也
有帮助,赞一个