标签:
代码:
#include <iostream>
#include <queue>
#include <cstring>
#include <cstdio>
using namespace std;
char c[50][50][50];
int vis[50][50][50]; //对访问过的点进行标记
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int i, k, j, x, y, n, m, sx, sy,sz; //用sx,sy,sz来表示起点S的三维坐标
struct T { //x,y,z表示任意点的坐标,cnt表示到达此点时的步数
int z;
int x;
int y;
int cnt;
}now, eed;
int can(struct T a) {//约束条件
if(c[a.z][a.x][a.y] == '#' || a.z <= 0 || a.z > k || a.x <= 0 || a.x > n || a.y <= 0 || a.y > m || vis[a.z][a.x][a.y])
return 0;
return 1;
}
int bfs()//广度优先搜索
{
queue<T> maze;
memset(vis, 0, sizeof(vis));
now.z = sz; now.x = sx; now.y = sy; now.cnt = 0;
maze.push(now); vis[now.z][now.x][now.y] = 1;
while( !maze.empty())
{
now = maze.front();
if(c[now.z][now.x][now.y] == 'E') return now.cnt; //找到终点,返回终点的cnt值
eed.cnt = now.cnt + 1;
for(i = 0; i < 4; i++) { //二维平面内向四个方向搜索, 即north, south, east, west
eed.z = now.z;
eed.x = now.x + dir[i][0];
eed.y = now.y + dir[i][1];
if(can(eed))//如果符合条件,就放到队列中
{
maze.push(eed);
vis[eed.z][eed.x][eed.y] = 1;
}
}
//二维平面的上方,即up
eed.z = now.z + 1;
eed.x = now.x;
eed.y = now.y;
if(can(eed))
{
maze.push(eed);
vis[eed.z][eed.x][eed.y] = 1;
}
//二维平面的下方,即down
eed.z = now.z - 1;
eed.x = now.x;
eed.y = now.y;
if(can(eed))
{
maze.push(eed);
vis[eed.z][eed.x][eed.y] = 1;
}
maze.pop();
}
return -1;
}
int main()
{
while(scanf("%d %d %d", &k, &n, &m) && k+n+m != 0) {
for(int i = 1; i <= k; i++) {
for(int j = 1; j <= n; j++) {
for(int a = 1; a <= m; a++) {
cin >> c[i][j][a];
if(c[i][j][a] == 'S')
{
sz = i;
sx = j;
sy = a;
}
}
}
}
int result = bfs();
if(result == -1) printf("Trapped!\n");
else printf("Escaped in %d minute(s).\n", result);
}
return 0;
}标签:
原文地址:http://blog.csdn.net/bao_libra/article/details/45485671