pku 2251 Dungeon Master BFS

本文介绍了一道经典的三维迷宫最短路径问题,并通过BFS算法进行解答。该问题来源于POJ在线评测系统,作者分享了从错误的DFS尝试到正确使用BFS的过程及完整代码实现。

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

http://poj.org/problem?id=2251

很简单的求最短路径的BFS题目,才开始自己写了各DFS直接性TLE。。。

三维的,就是多加了两个方向罢了,再处理的时候就按i,j,k来;

View Code
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#define maxn 33
using namespace std;

struct node
{
    int x,y,z;
    int len;
}s;
char map[maxn][maxn][maxn];
bool vt[maxn][maxn][maxn];
int l,r,c,ans;
bool flag;
int dir[6][3] = {{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
int bfs()
{
    int i;
    node t;
    queue<node>q;
    while (!q.empty()) q.pop();
    q.push(s);
    vt[s.x][s.y][s.z] = true;
    while (!q.empty())
    {
        node cur = q.front();
        q.pop();
        if (map[cur.x][cur.y][cur.z] == 'E')
        {
            return cur.len;
        }
        for (i = 0; i < 6; ++i)
        {
            t.x = cur.x + dir[i][0];
            t.y = cur.y + dir[i][1];
            t.z = cur.z + dir[i][2];
            if (t.x >= 0 && t.x < l && t.y >= 0 &&t.y < r && t.z >= 0 && t.z < c && map[t.x][t.y][t.z] != '#' && !vt[t.x][t.y][t.z])
            {
                vt[t.x][t.y][t.z] = true;
                t.len = cur.len + 1;
                q.push(t);
            }
        }
    }
    return -1;
}
int main()
{
    //freopen("in.txt","r",stdin);
    int i,j,k;
    while (scanf("%d%d%d",&l,&r,&c))
    {
        if (!l && ! r && !c) break;
        for (i = 0; i < l; ++i)
        {
            for (j = 0; j < r; ++j)
            {
                scanf("%s",map[i][j]);
                for (k = 0; k < c; ++k)
                {
                    if (map[i][j][k] == 'S')
                    {
                        s.x = i; s.y = j;
                        s.z = k; s.len = 0;
                    }
                }
            }
        }
        memset(vt,false,sizeof(vt));
        int l = bfs();
        if (l == -1)
        printf("Trapped!\n");
        else
        printf("Escaped in %d minute(s).\n",l);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值