【POJ】[2251]Dungeon Master

文章字数:261

问题描述

问题分析

三维BFS,不算难题
这一题数据给的非常严
DFS必然超时 (不是很喜欢POJ这样子-.-)
注意标记已遍历要放在push前
否则也会把一个点加入队列多次
导致内存超限或者时间超限
-.-就是这么严

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<cstdio>
#include<queue>
using namespace std;
int movet[6]= {0,0,0,0,1,-1};
char map[32][32][32];
bool flag[32][32][32];
struct node {
    int l,r,c,cnt;
} t,temp;
int L,R,C;
int sl,sr,sc;
int el,er,ec;
int bfs() {
    queue<node>q;
    t.l=sl,t.r=sr,t.c=sc,t.cnt=0;
    flag[t.l][t.r][t.c]=true;
    q.push(t);
    while(!q.empty()) {
        t=q.front();
        for(int i=0; i<6; i++) {
            temp.l=t.l+movet[i],temp.r=t.r+movet[(i+2)%6],temp.c=t.c+movet[(i+4)%6],temp.cnt=t.cnt+1;
            if(temp.l==el&&temp.r==er&&temp.c==ec)
                return temp.cnt;
            else if(temp.l>=0&&temp.l<L&&temp.r>=0&&temp.r<R&&temp.c>=0&&temp.c<C&&map[temp.l][temp.r][temp.c]!='#'&&!flag[temp.l][temp.r][temp.c]) {
                flag[temp.l][temp.r][temp.c]=true;
                q.push(temp);
            }
        }
        q.pop();
    }
    return -1;
}
int main() {
    while(scanf("%d %d %d",&L,&R,&C),L&&R&&C) {
        getchar();
        for(int i=0; i<L; i++) {
            for(int j=0; j<R; j++) {
                for(int k=0; k<C; k++) {
                    flag[i][j][k]=false;
                    scanf("%c",&map[i][j][k]);
                    if(map[i][j][k]=='S')
                        sl=i,sr=j,sc=k;
                    else if(map[i][j][k]=='E')
                        el=i,er=j,ec=k;
                }
                getchar();
            }
            getchar();
        }
        int res=bfs();
        if(res<0)
            printf("Trapped!\n");
        else
            printf("Escaped in %d minute(s).\n",res);
    }
    return 0;
}

该内容采用 CC BY-NC-SA 4.0 许可协议。

如果对您有帮助或存在意见建议,欢迎在下方评论交流。

加载中...