您的位置:首页 > 其它

走迷宫1 bnu 1054

2013-12-01 18:24 218 查看
走迷宫是很有趣的一种游戏,能够锻炼人的记忆力和思维.现在,HK被困在一个迷宫里面了,请你帮助他找到一条最短的路径,能够让他走出迷宫.

迷宫使用一个N*M的矩阵来描述,矩阵中用'.'代表空格可以通行,用'*'代表障碍物,用'S'代表出发点,用'T'代表出口.例如下面的一个矩阵就描述了一个8*8的迷宫

.....T..
..*****.
......*.
*.***.*.
......*.
.****.*.
S..*....
........

每个字符代表1个格子,HK只能在格子间按上下左右的方向移动

Input

每个输入文件只包含一组输入数据.
每组数据第一行是两个正整数N和M(N,M<=100).
接着是一个N*M的矩阵.

Output

如果HK能够走出迷宫,输出最少需要的步数;否则输出-1.

Sample Input

8 8
.....T..
..*****.
......*.
*.***.*.
......*.
.****.*.
S..*....
........

Sample Output

11

第一次queue,其实不难;
<注意:不知道是OJ的问题还是什么,#define N 好像会 RE,以后还是少用的呵。>


#include<iostream>
#include<queue>
#include<cstring>
using namespace std;

const int maxn = 100 + 10;
char a[maxn][maxn];
int vis[maxn][maxn],n,m;
int ax[5]={-1,0,1,0};
int ay[5]={0,-1,0,1};
struct Thing
{
int x, y;
int step;
}str;
Thing end,now;

int bfs ()
{
queue<Thing>que;
que.push(str);
while(!que.empty())
{
now=que.front();
if(now.x==end.x&&now.y==end.y)
{
return now.step;
}
que.pop();
for(int i=0;i<4;i++)
{
Thing temp;
temp.x=now.x+ax[i];
temp.y=now.y+ay[i];
temp.step=now.step+1;
if(temp.x >=0 &&temp.y<n&&temp.y>=0&&temp.y<m && !vis[temp.x][temp.y] && a[temp.x][temp.y]!='*')
{
vis[temp.x][temp.y]=1;
que.push(temp);
}
}
}
return -1;
}
int main ()
{
while(cin >> n >> m)
{
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin >> a[i][j];
if(a[i][j]=='S')
{
str.x=i;
str.y=j;
str.step=0;
vis[i][j]=1;
}
if(a[i][j]=='T')
{
end.x=i;
end.y=j;
}
}
}
//printf("-%d%d--%d%d-\n",str.x,str.y,end.x,end.y);
cout << bfs() << endl;
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: