本题为openjudge:
本题用到广搜:
#include<iostream>
#include<queue>
using namespace std;
int t,n,m,dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}},sx,sy,ex,ey;
char a[200][200];
struct point{
int x,y,step;
point(int xx,int yy,int st){
x=xx;
y=yy;
step=st;
}
};
int bfs(int x,int y){
queue<point> q;
q.push(point(x,y,0));
a[x][y]='#';
while(!q.empty()){
point p=q.front();
if(p.x==ex&&p.y==ey) return p.step;
for(int i=0;i<4;i++){
int dx=p.x+dir[i][0];
int dy=p.y+dir[i][1];
if(0<=dx&&dx<n&&0<=dy&&dy<m&&a[dx][dy]!='#'){
q.push(point(dx,dy,p.step+1));
a[dx][dy]='#';
}
}
q.pop();
}
return -1;
}
int main(){
int u;
cin>>t;
for(int k=1;k<=t;k++){
cin>>n>>m;
for(int i=0;i<n;i++) scanf("%s",a[i]);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(a[i][j]=='S'){
sx=i;
sy=j;
}
if(a[i][j]=='E'){
ex=i;
ey=j;
}
}
}
u=bfs(sx,sy);
if(u!=-1) cout<<u<<endl;
else if(u==-1) cout<<"oop!"<<endl;
}
return 0;
}