problem description
有一个二维迷宫,n行m列,‘s’表示迷宫的起点,‘T’表示迷宫的终点,‘#’表示围墙,‘.’表示通路。
现在从S出发,你不能穿墙,问到达终点T最少需要多少步?
输入格式
第一行输入n,m(1<=n,m<=50)表示迷宫的行列大小。
接下来输入n行字符串表示迷宫。
输出格式
一个整数,表示走出迷宫所需的最小步数,若走不出迷宫则输出 -1。
样例输入1
2 3 S.# ..T
样例输出1
3
样例输入2
3 3 S.# .#. .#T
样例输出2
-1
# include <cstdio>
# include <stdio.h>
# include <iostream>
# include <queue>
using namespace std;
const int maxn=1000;
typedef struct node {
int x;
int y;
int f;
node (int a,int b,int c)//这里面参数要是不同的
{x=a;y=b;f=c;}//将坐标看做结构体在队列中操作
}node;
queue<node>q;//q里面放的是结构体
int m,n;
char map[maxn][maxn];
int vis[maxn][maxn];
int s[2][2];
int val;
char ch;
int dp[4][2]={1,0,-1,0,0,1,0,-1};
int bfs(int x,int y,int f)
{
q.push(node(x,y,f));
vis[x][y]=1;
while (!q.empty())//这里去(!q.empty())
{
node p=q.front();
q.pop();
if (p.x==s[1][0]&&p.y==s[1][1])
return p.f;
for (int i=0;i<4;++i)
{
int x=p.x+dp[i][0];
int y=p.y+dp[i][1];
if (x<0||y<0||x>m-1||y>n-1||vis[x][y]==1||map[x][y]=='#') continue;
q.push(node(x,y,p.f+1));//这里是p.f+1,你要考虑到这个深度相同的
vis[x][y]=1;
}
}
return -1;
}
int main ()
{
cin>>m>>n;
ch=getchar();
for (int i=0;i<m;++i)
{
for (int j=0;j<n;++j)
{
cin>>map[i][j];
if (map[i][j]=='S') {s[0][0]=i;s[0][1]=j;}
if (map[i][j]=='T') {s[1][0]=i;s[1][1]=j;}
}
ch=getchar();
}
int t=bfs(s[0][0],s[0][1],0);
printf ("%d\n",t);
return 0;
}