POJ 2251 Dungeon Master(BFS例题)

用STL的queue实现BFS,最基础的题目了,不多说上代码

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>

#define MAXN 35

using namespace std;

int lv,n,m,sta_x,sta_y,sta_z;
char maze[MAXN][MAXN][MAXN];
int op[7][3] = {{0,0,0},{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
bool mark[MAXN][MAXN][MAXN];

struct node
{
int z;
int x;
int y;
int step;
};

void find_point()
{
for(int i = 0;i < lv;i ++)
{
for(int j = 0;j < n;j ++)
{
for(int k = 0;k < m;k ++)
{
if(maze[i][j][k] == 'S')
{
sta_x = j;
sta_y = k;
sta_z = i;
}
}
}
}
}

void bfs()
{
bool flag = false;
memset(mark , false , sizeof(mark));
mark[sta_z][sta_x][sta_y] = true;
queue<node>myQueue;
node st;
st.z = sta_z; st.x = sta_x; st.y = sta_y; st.step = 0;
myQueue.push(st);
while(!myQueue.empty())
{
node tmp = myQueue.front();
myQueue.pop();
for(int i = 1;i <= 6;i ++)
{
int tz = tmp.z + op[i][0];
int tx = tmp.x + op[i][1];
int ty = tmp.y + op[i][2];
if(tz >=0 && tz < lv && tx >=0 && tx < n && ty >=0 && ty < m && !mark[tz][tx][ty])
{
if(maze[tz][tx][ty] != '#')
{
if(maze[tz][tx][ty] == 'E')
{
printf("Escaped in %d minute(s).\n",tmp.step + 1);
return ;
}
mark[tz][tx][ty] = true; node now;
now.z = tz; now.x = tx; now.y = ty;
now.step = tmp.step + 1;
myQueue.push(now);
}
}
}
}
printf("Trapped!\n");
}

int main()
{
while(cin>>lv>>n>>m && (lv || n || m))
{
for(int i = 0;i < lv;i ++)
for(int j = 0;j < n;j ++)
scanf("%s",maze[i][j]);
find_point();
bfs();
}
return 0;
}

POJ 2251 Dungeon Master(BFS例题)

https://rucer.cn/2014-05/poj-2251/

作者

Ferris Tien

发布于

2014-05-04

更新于

2024-10-19

许可协议