走迷宫1
1000ms
65535KB
64-bit integer IO format:
%lld Java class name:
Main
Font Size:
走迷宫是很有趣的一种游戏,能够锻炼人的记忆力和思维.现在,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
Source
Author
HK@Sphinx
Tags ( Click to see )
裸BFS
#include"queue"
#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"
using namespace std;
char maze[105][105];
int N,M;
int move[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
bool vis[105][105];
bool is_block(int x,int y)
{
if(x<0 || x>=N || y<0 || y>=M)
{
return true;
}
if(maze[x][y] == '*')
{
return true;
}
return false;
}
struct node
{
int x,y,step;
};
queue <node> q;
int bfs(int x,int y)
{
while(!q.empty())
{
q.pop();
}
node now;
now.x = x;
now.y = y;
now.step = 0;
vis[x][y] = true;
q.push(now);
while(!q.empty())
{
node nnew = q.front();
q.pop();
if(maze[nnew.x][nnew.y] == 'T')
{
return nnew.step;
}
for(int i = 0;i < 4;i++)
{
int xx = nnew.x + move[i][0];
int yy = nnew.y + move[i][1];
if(!is_block(xx,yy) && !vis[xx][yy])
{
node n;
n.x = xx;
n.y = yy;
n.step = nnew.step + 1;
vis[xx][yy] = true;
q.push(n);
}
}
}
return -1;
}
int main()
{
while(~scanf("%d%d",&N,&M))
{
for(int i = 0;i < N;i++)
{
scanf("%s",maze[i]);
}
memset(vis,false,sizeof(vis));
for(int i = 0;i < N;i++)
{
for(int j = 0;j < M;j++)
{
if(maze[i][j] == 'S')
{
printf("%d\n",bfs(i,j));
break;
}
}
}
}
return 0;
}