POJ2251 Dungeon Master

题目:

你被困在一个3D地牢中且继续寻找最短路径逃生!地牢由立方体单位构成,立方体单位中有的会充满岩石。向上下前后左右移动一个单位需要一分钟。你不能向对角线的四个方向移动且迷宫四周环绕着许多岩石。 

是否可以逃出地牢?如果可以,则需要多少时间? 

输入:

输入的第一行包含一个数,表示地牢的数量。

每个地牢的描述,其第一行包含三个数L,R和C(均小于等于30)。

L表示地牢的层数;R和C分别表示每层地牢的行与列的大小。
随后输入地牢的层数L,每层中包含R行,每行中包含C个字符。
每个字符表示地牢的一个单元。'#'表示岩石单元,'.'表示空白单元。你的起始位置在点'S',出口为'E'。
每层地牢的输入后都有一个空行。当L,R和C均为0时,输入结束。

输出:

每个迷宫对应一行输出。

  如果可以逃生,则输出如下
Escaped in x minute(s).
  x为最短脱离时间。

  如果无法逃生,则输出如下
Trapped!

样例:

POJ2251 Dungeon Master

分析:BFS模板题,只不过二维变成三维,注意把出口视为可通过

ac代码如下:

#include<iostream>
#include<sstream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<numeric>
#include<cmath>
#include<queue>
#include<vector>
#include<set>
#include<cctype>
#define PI acos(-1.0)
const int INF = 0x3f3f3f;
const int NINF = -INF - 1;
typedef long long ll;
using namespace std;
int L, R, C;
struct Maze
{
    int x, y, z;
}m;
char maze[35][35][35];
int d[35][35][35];
int sx, sy, sz, ex, ey, ez;
int dx[6] = {1, -1, 0, 0, 0, 0}, dy[6] = {0, 0, 1, -1, 0, 0}, dz[6] = {0, 0, 0, 0, 1, -1};
int bfs()
{
    queue <Maze> q;
    for (int i = 0; i < L; ++i)
    {
        for (int j = 0; j < R; ++j)
        {
            for (int k = 0; k < C; ++k)
                d[i][j][k] = INF;
        }
    }
    d[sx][sy][sz] = 0;
    m.x = sx, m.y = sy, m.z = sz;
    q.push(m);
    while (q.size())
    {
        Maze temp = q.front();
        q.pop();
        if (temp.x == ex && temp.y == ey && temp.z == ez) break;
        for (int i = 0; i < 6; ++i)
        {
            int nx = temp.x + dx[i], ny = temp.y + dy[i], nz = temp.z + dz[i];
            if ((nx >= 0 && nx < L) && (ny >= 0 && ny < R) && (nz >= 0 && nz < C) && d[nx][ny][nz] == INF && maze[nx][ny][nz] != '#')
            {
                Maze ans;
                ans.x = nx, ans.y = ny, ans.z = nz;
                q.push(ans);
                d[nx][ny][nz] = d[temp.x][temp.y][temp.z] + 1;
            }
        }
    }
    return d[ex][ey][ez];
}
int main()
{
    while (cin >> L >> R >> C)
    {
        if (L == 0 && R == 0 && C == 0) break;
        for (int i = 0; i < L; ++i)
        {
            for (int j = 0; j < R; ++j)
            {
                for (int k = 0; k < C; ++k)
                {
                    cin >> maze[i][j][k];
                    if (maze[i][j][k] == 'S')
                        sx = i, sy = j, sz = k;
                    if (maze[i][j][k] == 'E')
                        ex = i, ey = j, ez = k;
                }
            }
            getchar();
        }
        int num = bfs();
        if (num != INF)
            cout << "Escaped in " << num << " minute(s)." << endl;
        else
            cout << "Trapped!" << endl;
    }
    return 0;
}