POJ 2251 Dungeon Master(BFS)

Dungeon Master

#include<iostream>
#include<string.h>
#include<string>
#include<stdio.h>
#include<queue>
using namespace std;

int l, r, c,ans;

int map[32][32][32];
bool v[32][32][32];

int dl[6] = { 0, 0, 0, 0, 1, -1 };
int dx[6] = { -1, 0, 0, 1, 0, 0 };
int dy[6] = { 0, -1, 1, 0, 0, 0 };

struct point {
    int l;
    int x;
    int y;
    int s;
} beg;

queue<point> que;
int bfs() {
    int ans = -1;
    while (!que.empty()) {
        point cnt = que.front();
        que.pop();

        if (map[cnt.l][cnt.x][cnt.y] == 'E') {
            ans = cnt.s;
            break;
        }

        for (int i = 0; i < 6; i++) {
            point np = { cnt.l + dl[i], cnt.x + dx[i], cnt.y + dy[i], cnt.s + 1 };

            if (np.l >= 0 && np.l < l&& np.x >= 0 && np.x < r && np.y >= 0 && np.y < c) {
                if (map[np.l][np.x][np.y] != '#' && v[np.l][np.x][np.y] == 0) {
                    que.push(np);
                    v[np.l][np.x][np.y] = 1;
                }
            }
        }
    }

    while (!que.empty()) {//清空队列
        que.pop();
    }
    return ans;
}

int main() {
   // freopen("data.in", "r", stdin);
    while (scanf("%d%d%d", &l, &r, &c)) {
        memset(v, 0, sizeof(v));
        getchar();//吃掉回车
        if (l == 0) {
            return 0;
        }

        for (int i = 0; i < l; i++) {
            for (int j = 0; j < r; j++) {
                for (int k = 0; k < c; k++) {
                    map[i][j][k] = getchar();
                    if (map[i][j][k] == 'S') {
                        beg.l = i, beg.x = j, beg.y = k, beg.s = 0;
                        v[i][j][k] = 1;
                    }
                }
                getchar();//吃掉回车
            }
            getchar();//吃掉空行回车
        }

        que.push(beg);
        int ans = bfs();
        if (ans == -1) {
            printf("Trapped!\n");
        } else {
            printf("Escaped in %d minute(s).\n", ans);
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值