[POJ2251]Dungeon Master(BFS)

本文介绍了一种使用三维宽度优先搜索(BFS)解决迷宫问题的方法,并提供了详细的C++实现代码。通过定义节点结构体和方向数组,利用队列进行搜索,找到从起点到终点的最短路径。

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

思路

以前做过几道二维坐标的BFS这道题是三维的道理一样,别忘加一个vis数组表示是否遍历过,用搜索最短路径的基本思路做就行了。

代码

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

const int maxn = 35;

char map[maxn][maxn][maxn];
bool vis[maxn][maxn][maxn];
int L, R, C;
int bx, by, bz;       //起点的坐标
int ex, ey, ez;       //终点的坐标

struct node {
    int x, y, z;
    int step;
};

int dir[][3] = {{1, 0, 0}, {-1, 0, 0}, {0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}};

bool check(int x, int y, int z) {
    return (x >= 0 && x < C && y >= 0 && y < R && z >= 0 && z < L && !vis[z][y][x] && map[z][y][x] != '#');
}

int bfs() {
    queue<node> qu;
    memset(vis, false, sizeof(vis));
    node v, t, next;
    t.x = bx;
    t.y = by;
    t.z = bz;
    t.step = 0;
    qu.push(t);
    while(!qu.empty()) {
        v = qu.front(); qu.pop();
        for(int i = 0; i < 6; i++) {
            next.x = v.x + dir[i][0];
            next.y = v.y + dir[i][1];
            next.z = v.z + dir[i][2];
            next.step = v.step + 1;
            if (ex == next.x && ey == next.y && ez == next.z) {
                return next.step;
            }
            if (check(next.x, next.y, next.z)) {
                vis[next.z][next.y][next.x] = true;
                qu.push(next);
            }
        }
    }
    return -1;
}

int main() {
    //freopen("input.txt", "r", stdin);
    while(scanf("%d%d%d", &L, &R, &C) != EOF && L) {
        for(int l = 0; l < L; l++) {
            for(int r = 0; r < R; r++) {
                scanf("%s", map[l][r]);
                for(int c = 0; c < C; c++) {
                    if (map[l][r][c] == 'S')  {
                        bx = c;
                        by = r;
                        bz = l;
                    }
                    else if (map[l][r][c] == 'E') {
                        ex = c;
                        ey = r;
                        ez = l;
                    }
                }
            }
        }
        int ans;
        if ((ans = bfs()) != -1)  printf("Escaped in %d minute(s).\n", ans);
        else printf("Trapped!\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值