POJ 2251 Dungeon Master

这是一道结合了地牢元素的最短路径问题,不同于常规的BFS,需要在3D空间中考虑上下移动,同时进行多维度搜索。题目要求在分层的3D图中找到最短路径,通过扩展BFS策略来解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

嘛 挺进地牢OI版?

这题挺有趣的,并不是传统意义上的BFS

而是给了你一个分层的3D图,让你在这个图上找出一条最短路

跟传统BFS相比 我们要增加两个方向:上和下

我们所在的层数就是对应Z轴的坐标

剩下就是一个三维的BFS了


#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

const int dx[7] = {0, 0, 0, 0, 0, 1, -1};
const int dy[7] = {0, 0, 0, 1, -1, 0, 0};
const int dz[7] = {0, 1, -1, 0, 0, 0, 0};

char map[40][40][40];
bool vis[40][40][40];
int stx, sty, stz, edx, edy, edz, k, n, m;
struct data {
    int x, y, z;
    int step;
};

inline bool check(int x, int y, int z) {
    if(x < 0 || y < 0 || z < 0 || x >= k || y >= n || z >= m) return false;
    else if(map[x][y][z] == '#' || vis[x][y][z]) return false;
    return true;
}

inline int bfs() {
    queue<data> Q;
    data now, next;
    now.x = stx, now.y = sty, now.z = stz, now.step = 0;
    vis[stx][sty][stz] = true; Q.push(now);
    while(!Q.empty()) {
        now = Q.front(); Q.pop();
        if(now.x == edx && now.y == edy && now.z == edz) return now.step;
        for(int i = 1; i <= 6; ++i) {
            next.x = now.x + dx[i];
            next.y = now.y + dy[i];
            next.z = now.z + dz[i];
            next.step = now.step + 1;
            if(!check(next.x, next.y, next.z)) continue;
            vis[next.x][next.y][next.z] = true;
            Q.push(next);
        }
    } 
    return 0;
}

int main() {
    while(scanf("%d%d%d", &k, &n, &m) && (n || m || k)) {
        memset(vis, false, sizeof(vis));
        for(int i = 0; i < k; ++i) for(int j = 0; j < n; ++j) {
            scanf("%s", map[i][j]);
            for(int r = 0; r < m; ++r) {
                if(map[i][j][r] == 'S') stx = i, sty = j, stz = r;
                else if(map[i][j][r] == 'E') edx = i, edy = j, edz = r;
            }
        }
        int ans = bfs();
        if(ans) printf("Escaped in %d minute(s).\n", ans);
        else puts("Trapped!");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值