#include<iostream>
#include<cstring>
#include<queue>
#include<cstdio>
using namespace std;
int vis[81][81];
char map[81][81];
int next_Step[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
struct point{
int x;
int y;
int step;
};
int m,n;
int sx,sy,ex,ey;
queue<point> q;
void bfs(){
vis[sx][sy]=1;
point p;
p.x=sx;
p.y=sy;
p.step=0;
q.push(p);
while(!q.empty()){
point temp;
temp=q.front();
q.pop();
if(temp.x==ex && temp.y==ey){
cout<<temp.step<<endl;
}
for(int i=0;i<4;i++){
int nx=temp.x+next_Step[i][0];
int ny=temp.y+next_Step[i][1];
if(nx>=1 && nx<=m && ny>=1 && ny<=n && !vis[nx][ny] && map[nx][ny]!='#'){
point pt;
pt.x=nx;
pt.y=ny;
pt.step=temp.step+1;
vis[nx][ny]=1;
q.push(pt);
}
}
}
}
int main(){
memset(vis,0,sizeof(vis));
freopen("in2.txt","r",stdin);
while(~scanf("%d %d",&m,&n) && m!=0 && n!=0){
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
cin>>map[i][j];
if(map[i][j]=='S'){
sx=i;
sy=j;
}
if(map[i][j]=='G'){
ex=i;
ey=j;
}
}
}
bfs();
}
return 0;
}
输入的话添加文件in2.txt
5 5
#S###
..##.
#.###
..###
..G##
输出最短路径为9,与》》》》》DFS实现迷宫,打印路径输出步数的图一样