一个N*M的迷宫,*代表墙,“.”代表空地,S是起点,T是终点。求从S到T的最短距离的步数,无法到达输出-1;
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=100;
struct node
{
int x,y;
int step;
}Node,S,T;
int m,n;
char Map[maxn][maxn];
bool vis[maxn][maxn];
int X[4]={0,0,1,-1};
int Y[4]={1,-1,0,0};
bool judge(int x,int y)
{
if(x<0||y<0||x>=n||y>=m)
return false;
if(Map[x][y]=='*')
return false;
if(vis[x][y]==true)
return false;
return true;
}
int BFS()
{
queue<node> q;
q.push(S);
while(!q.empty())
{
node top=q.front();//取队首
q.pop();
if(top.x==T.x&&top.y==T.y)
{
return top.step;
}
for(int i=0;i<4;i++)//入队
{
int xx=top.x+X[i];
int yy=top.y+Y[i];
if(judge(xx,yy))
{
Node.x=xx;
Node.y=yy;
Node.step=top.step+1;
q.push(Node);
vis[xx][yy]=true;
}
}
}
return -1;
}
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++)
{
getchar();//读取换行符
for(int j=0;j<m;j++)
{
Map[i][j]=getchar();
if(Map[i][j]=='S')
{
S.x=i;
S.y=j;
}
if(Map[i][j]=='T')
{
T.x=i;
T.y=j;
}
}
Map[i][m+1]='\0';
}
S.step=0;//初始化步数
cout<<BFS()<<endl;
return 0;
}