题目链接:
传送门
#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 31;
struct node { int x, y, z; };
//操作数组
node op[6] = { {0,0,1},{0,0,-1} ,{1,0,0}, {-1,0,0} ,{0,1,0} ,{0,-1,0} };
//定义三维坐标和起始点
int len[N][N][N], l, r, c, sx, sy, sz, ex, ey, ez;
//用于标记已搜过的结点
int used[N][N][N];
//一个判断该点是否在合法区域内的函数
bool inMap(int x, int y, int z)
{
return x >= 1 && x <= c && y >= 1 && y <= r && z >= 1 && z <= l;
}
//bfs函数体
void bfs(int x, int y, int z)
{
//创建队列如果没有
queue<node> q;
node start= {x,y,z};
q.push(start);
//把起点标记为已查
used[x][y][z] = 1;
len[x][y][z] = 0;
//在队列不为空的情况下
while (!q.empty())
{
//获取当前顶部的元素
node cur = q.front();
//向几个方向进行搜索
for (int i = 0; i < 6; i++)
{
//对点的各个坐标进行处理
int curX = cur.x + op[i].x;
int curY = cur.y + op[i].y;
int curZ = cur.z + op[i].z;
//判断是否符合条件(是否已被搜索,是否超出地图)
if (inMap(curX, curY, curZ) && !used[curX][curY][curZ])
{
used[curX][curY][curZ] = 1;
len[curX][curY][curZ] = len[cur.x][cur.y][cur.z] + 1;
//把新的点压入栈中
node news= {curX,curY,curZ};
q.push(news);
}
}
q.pop();
}
}
int main()
{
while (cin >> l >> r >> c)
{
if (l == 0 && r == 0 && c == 0) break;
memset(len, 0, sizeof(len));
memset(used, 0, sizeof(used));
for (int i = 1; i <= l; i++)
for (int j = 1; j <= r; j++)
for (int k = 1; k <= c; k++)
{
char a;
cin >> a;
if (a == 'S')
{
sx = k;
sy = j;
sz = i;
}
else if (a == 'E')
{
ex = k;
ey = j;
ez = i;
}
else if (a == '#') used[k][j][i] = 1;
else used[k][j][i] = 0;
}
bfs(sx, sy, sz);
if (len[ex][ey][ez] == 0)
cout << "Trapped!" << endl;
else
cout << "Escaped in " << len[ex][ey][ez] << " minute(s)." << endl;
}
return 0;
}
这道题是一个三维的搜索,这道题因为是找最短的路所以感觉bfs会比较好做。向上下左右前后进行搜索,最后查看结束点的最短路径长度,如果是0则说明这是一个不连通的点。也就是Trapped的情况,否则输出最短的路长。