poj 2251 Dungeon Master

dfs一定会超时的。

用bfs。

/*
POJ: 2251 Dungeon Master
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

#define M 35

using namespace std;

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

struct Node {
    int x, y, z;
    int step;
    
    Node (int _x, int _y, int _z, int _step) : x(_x), y(_y), z(_z), step(_step) {}
};

char map[M][M][M];
bool visited[M][M][M];
int l, r, c;
int startx, starty, startz;
queue<struct Node> que;

bool check(int x, int y, int z)
{
    if(x >= 0 && x < l && y >= 0 && y < r && z >= 0 && z < c)
        return true;
    return false;
}

int bfs(int x, int y, int z)
{
    while(!que.empty())
        que.pop();
    memset(visited, false, sizeof(visited));
    
    que.push(Node(x, y, z, 1));
    visited[x][y][z] = true;   
    while(!que.empty()) {
        struct Node tmp = que.front();
        que.pop();
        for(int i = 0; i < 6; i++) {
            int tmpx = tmp.x + dir[i][0];
            int tmpy = tmp.y + dir[i][1];
            int tmpz = tmp.z + dir[i][2];
            if(check(tmpx, tmpy, tmpz) && !visited[tmpx][tmpy][tmpz]) {
                if(map[tmpx][tmpy][tmpz] == 'E')
                    return tmp.step;
                else if(map[tmpx][tmpy][tmpz] == '.') {
                    que.push(Node(tmpx, tmpy, tmpz, tmp.step + 1));
                    visited[tmpx][tmpy][tmpz] = true;
                }
            }
        }
    }
    return -1;
}            
            
int main()
{
    //freopen("data.in", "rb", stdin);
    while(scanf("%d%d%d", &l, &r, &c) != EOF && (l || r || c)) {
        for(int i = 0; i < l; i++) {
            for(int j = 0; j < r; j++) {
                for(int k = 0; k < c; k++) {
                    char ch;
                    while(cin >> ch, ch == '\n');
                    map[i][j][k] = ch;
                    if(map[i][j][k] == 'S') {
                        startx = i;
                        starty = j;
                        startz = k;
                    }
                }
            }
        }
    
        int res = bfs(startx, starty, startz);
        if(res == -1)
            printf("Trapped!\n");
        else
            printf("Escaped in %d minute(s).\n", res);
    }

    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值