UVA532 Dungeon Master

来源:互联网 发布:北航软件工程硕士学费 编辑:程序博客网 时间:2024/04/26 14:49

问题链接:UVA532 Dungeon Master。

题意简述:三维空间地牢(迷宫),每个点由'.'(可以经过)、'#'(墙)、'S'(起点)和'E'(终点)组成。移动方向有上、下、左、右、前和后6个方向。每移动一次耗费1分钟,求从'S'到'E'最快走出时间。不同L层,相同RC处是连通的。

问题分析:一个三维迷宫,典型的BFS问题。在BFS搜索过程中,走过的点就不必再走了,因为这次再走下去不可能比上次的步数少。

程序中,使用了一个队列来存放中间节点,但是每次用完需要清空。需要注意的一点,为了编程方便,终点'E'置为'.'。

需要说明的一点,用C++语言的输入比起C语言的输入,程序简洁方便。

AC的C++语言程序如下:

/* UVA532 Dungeon Master */#include <iostream>#include <queue>using namespace std;const int DIRECTSIZE = 6;struct direct {    int dx;    int dy;    int dz;} direct[DIRECTSIZE] =    {{-1, 0, 0}, {1, 0, 0}, {0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}};const int MAXN = 50;char cube[MAXN][MAXN][MAXN];struct node {    int x, y, z, level;};int L, R, C;node start, e2;int ans;void bfs(){    queue<node> q;    ans = -1;    q.push(start);    while(!q.empty()) {        node front = q.front();        q.pop();        if(front.x == e2.x && front.y == e2.y && front.z == e2.z) {            ans = front.level;            break;        }        for(int i=0; i<DIRECTSIZE; i++) {            int nextx, nexty, nextz;            nextx = front.x + direct[i].dx;            if(0 > nextx || nextx >= L)                continue;            nexty = front.y + direct[i].dy;            if(0 > nexty || nexty >= R)                continue;            nextz = front.z + direct[i].dz;            if(0 > nextz || nextz >= C)                continue;            if(cube[nextx][nexty][nextz] == '.') {                cube[nextx][nexty][nextz] = '#';                node v;                v.x = nextx;                v.y = nexty;                v.z = nextz;                v.level = front.level + 1;                q.push(v);            }        }    }}int main(){    int i, j, k;    char c;    while(cin >> L >> R >> C) {        if(L == 0 && R == 0 && C == 0)            break;        for(i=0; i<L; i++) {            for(j=0; j<R; j++) {                for(k=0; k<C; k++) {                    cin >> c;                    cube[i][j][k] = c;                    if(c == 'S') {                        start.x = i;                        start.y = j;                        start.z = k;                        start.level = 0;                    } else if(c == 'E') {                        e2.x = i;                        e2.y = j;                        e2.z = k;                        cube[i][j][k] = '.';                    }                }            }        }        bfs();        if(ans == -1)            cout << "Trapped!\n";        else            cout << "Escaped in "<< ans << " minute(s)." << endl;    }    return 0;}




1 0
原创粉丝点击