Skip to content
Author: lllyouo
Date: 20250812
tag: 简单搜索
link: http://poj.org/problem?id=2251

问题描述

link

分析

参考代码

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

const int N = 30;
char g[N][N][N];
int dis[N][N][N];
int x, y, z;
int sx, sy, sz, ex, ey, ez;
int dx[6] = {1, -1, 0, 0, 0, 0};
int dy[6] = {0, 0, 1, -1, 0, 0};
int dz[6] = {0, 0, 0, 0, 1, -1};

struct Point {
    int x, y, z;
};

void bfs() {
    memset(dis, -1, sizeof(dis));
    dis[sx][sy][sz] = 0;
    queue<Point> q;
    q.push({sx, sy, sz});

    while (q.size()) {
        auto p = q.front();
        q.pop();

        for (int i = 0; i < 6; i++) {
            int nx = p.x + dx[i];
            int ny = p.y + dy[i];
            int nz = p.z + dz[i];

            if (nx < 0 || nx >= x || ny < 0 || ny >= y || nz < 0 || nz >= z) continue;
            if (g[nx][ny][nz] == '#') continue;
            if (dis[nx][ny][nz] != -1) continue;

            dis[nx][ny][nz] = dis[p.x][p.y][p.z] + 1;
            q.push({nx, ny, nz});
        }
    }

    if (dis[ex][ey][ez] == -1)
        cout << "Trapped!" << endl;
    else
        cout << "Escaped in " << dis[ex][ey][ez] << " minute(s)." << endl;
}

int main() {
    while (cin >> x >> y >> z) {
        if (x == 0 && y == 0 && z == 0) break;

        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                cin >> g[i][j];
            }
        }

        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                for (int k = 0; k < z; k++) {
                    if (g[i][j][k] == 'S') {
                        sx = i;
                        sy = j;
                        sz = k;
                    }
                    if (g[i][j][k] == 'E') {
                        ex = i;
                        ey = j;
                        ez = k;
                    }
                }
            }
        }

        bfs();
    }

    return 0;
}