描述
当你站在一个迷宫里的时候,往往会被错综复杂的道路弄得失去方向感,如果你能得到迷宫地图,事情就会变得非常简单。
假设你已经得到了一个n*m的迷宫的图纸,请你找出从起点到出口的最短路。
输入
第一行是两个整数n和m(1<=n,m<=100),表示迷宫的行数和列数。
接下来n行,每行一个长为m的字符串,表示整个迷宫的布局。字符’.‘表示空地,’#'表示墙,'S’表示起点,'T’表示出口。
输出
输出从起点到出口最少需要走的步数。
样例输入
3 3
S#T
.#.
…
样例输出
6
题目链接
思路:BFS板子
代码:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<queue>
#include<iostream>
using namespace std;
struct note
{
int x;
int y;
int f;
int s;
};
int nest[4][2]={{0,1},{0,-1},{-1,0},{1,0}};
int sx,sy,ex,ey;
int flag;
int n,m;
const int N=105;
int book[N][N];
char mp[N][N];
queue <note> que;
void bfs()
{
int tx,ty;
note temp;
temp.x=sx;
temp.y=sy;
temp.s=0;
temp.f=0;
que.push(temp);
book[sx][sy]=1;
while(!que.empty())
{
for(int k=0; k<4; k++)
{
temp=que.front();
tx=nest[k][0]+temp.x;
ty=temp.y+nest[k][1];
if(tx>=1 && tx<=n && ty>=1 && ty<=m && book[tx][ty]==0)
{
if(mp[tx][ty]=='.')
{
book[tx][ty]=1;
temp.x=tx;
temp.y=ty;
temp.s=temp.s+1;
que.push(temp);
}
if(tx==ex && ty==ey)
{
printf("%d\n",temp.s+1);
return;
}
}
}
que.pop();
}
}
int main()
{
scanf("%d %d",&n,&m);
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
cin>>mp[i][j];
if(mp[i][j]=='S')
{
sx=i;
sy=j;
}
else if(mp[i][j]=='T')
{
ex=i;
ey=j;
}
}
}
bfs();
return 0;
}