#include <iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
#define MAX 1000
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int n,m;
char A[MAX][MAX];
int d[MAX][MAX];//保存最近距离
int sx,sy;//起点
int ex,ey;//终点
int bfs();
int main(int argc, char** argv) {
freopen("test.txt","r",stdin);
cin>>n>>m;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
d[i][j]=-1;
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
char c;
cin>>c;
A[i][j]=c;
if(c=='S')
{
sx=i;
sy=j;
}
if(c=='G')
{
ex=i;
ey=j;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cout<<A[i][j]<<" ";
}
cout<<endl;
}
d[sx][sy]=0;
cout<<bfs()<<endl;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
printf("%4d ",d[i][j]);
}
cout<<endl;
}
return 0;
}
int bfs()
{
typedef pair<int,int> p;
int X[]={0,0,-1,1};
int Y[]={1,-1,0,0};
queue<p> q;
q.push(p(sx,sy));
while(!q.empty())
{
p point=q.front();
q.pop();
if(point.first==ex&&point.second==ey)
{
return d[point.first][point.second];
}
for(int j=0;j<=3;j++)
{
int a=point.first+X[j];
int b=point.second+Y[j];
if(a>=0&&a<n&&b>=0&&b<m)
{
if(A[a][b]!='#')
{
if(d[a][b]==-1)//未访问过
{
d[a][b]=d[point.first][point.second]+1;
q.push(p(a,b));
}
}
}
}
}
}
迷宫最短路径(bfs)
最新推荐文章于 2024-08-12 08:49:39 发布