Sample Input
1 5 5 S-### ----- ##--- E#--- ---##
Sample Output
9
//BFS 广度优先搜索
#include<stdio.h>
#include<queue>
using namespace std;
int vis[110][110];
int dir[4][2]={0,1,1,0,-1,0,0,-1};
char c[110][110];
int w,h,t;
struct list{
int x,y;
int step;
}a;
int mini=0;
queue<list> que; //定义队列
//que.push(a); 队尾进队列,a为进队列元素
//que.pop(); 队首出队列
//list temp=que.front(); 队首的元素
//int size=que.size(); 元素个数
//while(!que.empty())que.pop(); 重复使用时,初始化清空队列
int BFS(struct list a){
while(!que.empty()) que.pop();
list now,temp;
que.push(a);
int i;
while(!que.empty()){
now=que.front();
que.pop();
for(i=0;i<4;++i){
temp.x=now.x+dir[i][0];
temp.y=now.y+dir[i][1];
temp.step=now.step+1;
if(vis[temp.x][temp.y]==0){
if(temp.x>=0&&temp.x<w&&temp.y>=0&&temp.y<h){
if(c[temp.x][temp.y]=='E'){
return temp.step;
}
if(c[temp.x][temp.y]=='-'){
vis[temp.x][temp.y]=1;
que.push(temp);
}
}
}
}
}
return 0;
}
int main(void){
int i,j,k;
scanf("%d",&t);
for(i=0;i<t;++i){
mini=0;
scanf("%d %d\n",&h,&w);
for(j=0;j<h;++j){
for(k=0;k<w;++k){
scanf("%c",&c[k][j]);
vis[k][j]=0;
}
getchar();
}
for(j=0;j<h;++j){
for(k=0;k<w;++k){
if(c[k][j]=='S'){
a.x=k,a.y=j,a.step=0;
mini=BFS(a);
if(mini!=0){
printf("%d\n",mini);
}else{
printf("-1\n");
}
break;
}
}
if(k!=w)
break;
}
}
return 0;
}