# 迷宫最短路径问题（BFS）

``````#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
struct mig{
int tep;
int x,y;
char s;
}mg[100][100];
int main()
{
bool f[100][100];
memset(f,0,sizeof(f));
queue<mig> myq;
mig tt,cc;
int n,m,i,j,suf;                  //suf走出迷宫成功标记
cin>>n>>m;
for(i=0;i<n;i++)
for(j=0;j<m;j++){
cin>>mg[i][j].s;
mg[i][j].y=i;
mg[i][j].x=j;              //注意二维数组的[i][j]与坐标(x,y)相反
if(mg[i][j].s=='S') { mg[i][j].tep=0; f[i][j]=1; myq.push(mg[i][j]);}
if(mg[i][j].s=='#') f[i][j]=1;
}
while(!myq.empty())
{
tt=myq.front();
myq.pop();
i=tt.y;
j=tt.x;
if(i+1<n  && f[i+1][j]==0) {
if(mg[i+1][j].s=='G'){suf=1; break;}    //向下
f[i+1][j]=1;
cc.y=i+1;
cc.x=j;
cc.tep=tt.tep+1;
myq.push(cc);
}
if(i-1>=0 && f[i-1][j]==0) {
if(mg[i-1][j].s=='G'){suf=1; break;}     //向上
f[i-1][j]=1;
cc.y=i-1;
cc.x=j;
cc.tep=tt.tep+1;
myq.push(cc);
}
if(j+1<m  && f[i][j+1]==0) {
if(mg[i][j+1].s=='G'){suf=1; break;}      //向右
f[i][j+1]=1;
cc.y=i;
cc.x=j+1;
cc.tep=tt.tep+1;
myq.push(cc);
}
if(j-1>=0 && f[i][j-1]==0) {
if(mg[i][j-1].s=='G'){suf=1; break;}      //向左
f[i][j-1]=1;
cc.y=i;
cc.x=j-1;
cc.tep=tt.tep+1;
myq.push(cc);
}
}
if(suf==1) cout<<tt.tep+1<<endl;
else cout<<"no"<<endl;
return 0;
}``````
原文作者：BFS
原文地址: https://blog.csdn.net/specter11235/article/details/68947006
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。