POJ 2251 Dungeon Master (BFS)

31 篇文章 0 订阅

题目链接:Dungeon Master


解析:三维BFS模板题。

6个方向

开始想的太复杂了,水了好久,其实只要老老实照二维的套就完了。



AC代码:

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

int L, R, C;
string m[32][32];
bool vis[32][32][32];
int sx, sy, sz, ex, ey, ez;
int dir[6][3] = {1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1};    //6个方向
int ans;

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

void bfs(){
    queue<Node> q;
    vis[sx][sy][sz] = true;
    q.push(Node{sx, sy, sz, 0});
    while(!q.empty()){
        Node now = q.front(); q.pop();
        for(int i=0; i<6; i++){
            int x = now.x + dir[i][0];
            int y = now.y + dir[i][1];
            int z = now.z + dir[i][2];
            if(x < 0 || x >= L || y < 0 || y >= R || z < 0 || z >= C) continue;
            if(vis[x][y][z]) continue;
            if(m[x][y][z] == '#') continue;
            vis[x][y][z] = true;
            q.push(Node{x, y, z, now.step+1});
            if(x == ex && y == ey && z == ez){
                ans = now.step + 1;
                return ;
            }
        }
    }
    return ;
}

int main(){
//    freopen("in.txt", "r", stdin);
    while(scanf("%d%d%d", &L, &R, &C) == 3){
        if(L == 0 && R == 0 && C == 0) break;
        for(int i=0; i<L; i++)
            for(int j=0; j<R; j++){
                cin>>m[i][j];
                for(int k=0; k<m[i][j].size(); k++){
                    if(m[i][j][k] == 'S'){
                        sx = i;
                        sy = j;
                        sz = k;
                    }
                    if(m[i][j][k] == 'E'){
                        ex = i;
                        ey = j;
                        ez = k;
                    }
                }
            }
        memset(vis, false, sizeof(vis));
        ans = -1;
        bfs();
        if(ans == -1) puts("Trapped!");
        else printf("Escaped in %d minute(s).\n", ans);
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值