POJ_2251_(BFS)

B

POJ 2251

  • 三维bfs求最短路径
  • 方向从 东南西北 加入 上下
  • 注意L是层数的意思,从下层给到上层,
  • bfs模板 + vis三维标记 + tx ty tz 三维坐标
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
#include <iostream>
#include <queue>
#include <string.h>

using namespace std;

struct node {
int step;
int x,y,z;
node() {}
node (int a,int b,int c,int step) {
x = a; y = b; z = c; this->step = step;
}
};
char e[31][31][31];
int n,m,h;
int next1[6][3] = {0,0,1, 0,0,-1, 0,1,0, 1,0,0, 0,-1,0, -1,0,0};
int s_x,s_y,s_z;
int e_x,e_y,e_z;
bool vis[31][31][31];
queue<node> que;
int ans;
bool flag;
void init() {
memset(vis,0,sizeof vis);
memset(e,0,sizeof e);
while (!que.empty()) que.pop();
ans = 0;
}
void bfs() {
node t(s_x,s_y,s_z,0);
que.push(t);
vis[s_x][s_y][s_z] = 1;
while (!que.empty()) {
node cur = que.front();
que.pop();
for (int i=0; i<6; i++) {
int tx = cur.x + next1[i][0];
int ty = cur.y + next1[i][1];
int tz = cur.z + next1[i][2];
if ( tx<1 || tx>n || ty<1 || ty>m || tz<1 || tz>h) continue;
if (!vis[tx][ty][tz] && e[tz][tx][ty] == '.') {
node t(tx,ty,tz, cur.step+1 );
que.push(t);
vis[tx][ty][tz] = 1;
}
else if (!vis[tx][ty][tz] && e[tz][tx][ty] == 'E') {
flag = 1;
ans = cur.step+1;
return ;
}
}
}
flag = 0;
return ;
}
int main() {
// freopen("a.txt","r",stdin);
while ( cin >> h >> n >> m ) {
if (n==0 && m==0 && h==0) break;
init();
for (int i=1; i<=h; i++) {
for (int j=1; j<=n; j++) {
for (int k=1; k<=m; k++) {
cin >> e[i][j][k];
if (e[i][j][k] == 'S') {
s_z = i;
s_x = j;
s_y = k;
}
else if (e[i][j][k] == 'E') {
e_z = i;
e_x = j;
e_y = k;
}
}
}
}
bfs();
if (flag) printf("Escaped in %d minute(s).\n",ans);
else printf("Trapped!\n");
}
return 0;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!