输入样例:
3
3 4
.S..
###.
..E.
3 4
.S..
.E..
....
3 4
.S..
####
..E.
输出样例:
5
1
oop!
vis标记的修改,要在添加到队列前,不要在出队列后,否则会重复路过某地点。
#include<bits/stdc++.h>
using namespace std;
const int N=200+5;
int t,n,m,sx,sy,ex,ey;
char ch[N][N];
int vis[N][N];
struct node{
int x,y,w;
};
int dir[4][2]={1,0,0,1,-1,0,0,-1};
int check(int x,int y){
return x>0&&y>0&&x<=n&&y<=m;
}
void bfs(){
memset(vis,0,sizeof vis);
queue<node>q;
node start={sx,sy,0};
node next;
vis[start.x][start.y]=1;
q.push(start);
while(q.size()){
start=q.front();
q.pop();
if(start.x==ex&&start.y==ey){
cout<<start.w<<endl;
return;
}
for(int i=0;i<4;i++){
next.x=start.x+dir[i][0];
next.y=start.y+dir[i][1];
if(check(next.x,next.y)&&ch[next.x][next.y]!='#'&&!vis[next.x][next.y]){
next.w=start.w+1;
vis[next.x][next.y]=1;
q.push(next);
}
}
}
cout<<"oop!"<<endl;
}
int main(){
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>ch[i][j];
if(ch[i][j]=='S') sx=i,sy=j;
else if(ch[i][j]=='E') ex=i,ey=j;
}
}
bfs();
}
return 0;
}