POJ NO.2251 Dungeon Master(BFS,三维迷宫)

本文介绍了一种基于广度优先搜索(BFS)的三维迷宫逃脱算法实现,该算法能够找到从起点到终点的最短路径,适用于POJNO.2251问题。文章详细解释了算法思路,并提供了完整的C++代码实现。

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

问题描述:

给你一个三维地牢,‘.’代表可以走的点,‘#’代表不可走的点,‘S’代表开始点,‘E’代表结束点。问从‘S’开始能不能走出地牢,能的话要用多长时间,不能输出不能,输入输出见原题目。

题目链接:POJ NO.2251

思路:

多了一个方向,其他和普通bfs一样。

代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<queue>
#include<stack>
#include<cstring>
#include<string>
#include<vector>
#include<set>
#define INF 0x3f3f3f3f
#define PI 3.1415926
#define MAX 40

using namespace std;

struct node{
    char x, y, z;
    int t;
};
char mp[MAX][MAX][MAX];
int l, m, c, bx, by, bz;
int xx[]={1,-1,0,0,0,0};
int yy[]={0,0,0,0,-1,1};
int zz[]={0,0,-1,1,0,0};
bool visit[MAX][MAX][MAX];

int bfs(){
    memset(visit, false, sizeof(visit));
    queue<node> que;
    que.push((node){
             bx, by, bz,0
             });
    while(!que.empty()){
        node p = que.front();
        que.pop();
        if(mp[p.x][p.y][p.z] == 'E') return p.t;
        if(visit[p.x][p.y][p.z]) continue;
        visit[p.x][p.y][p.z] = true;
        for(int i = 0; i < 6; i++){
            node n;
            n.x = p.x + xx[i];
            n.y = p.y + yy[i];
            n.z = p.z + zz[i];
            n.t = p.t + 1;
            if(0 <= n.x && n.x < l && 0 <= n.y && n.y < m &&
            0 <= n.z && n.z < c && !visit[n.x][n.y][n.z] &&
            mp[n.x][n.y][n.z] != '#'){
                que.push(n);
            }
            }
    }
    return -1;
}

int main(){
    while(~scanf("%d%d%d", &l, &m, &c)){
            if(l + m + c == 0){
                break;
            }
        for(int i = 0; i < l; i++){
            for(int j = 0; j < m; j++){
                    scanf("%s", &mp[i][j]);
                for(int k = 0; k < c; k++){
                    if(mp[i][j][k] == 'S'){
                        bx = i, by = j, bz = k;
                    }
                }
            }
        }
    int res = bfs();
    if(res == -1){
        printf("Trapped!\n");
    }else
        printf("Escaped in %d minute(s).\n", res);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值