POJ 2251 Dungeon Master (BFS最短路)

三维空间里BFS最短路

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <sstream>
 5 #include <string>
 6 #include <algorithm>
 7 #include <list>
 8 #include <map>
 9 #include <vector>
10 #include <queue>
11 #include <stack>
12 #include <cmath>
13 #include <cstdlib>
14 using namespace std;
15 char mapp[40][40][40];
16 bool vis[40][40][40];
17 struct  Node {
18     int f,r,c,step;
19 } s,e;
20 int l,r,c;
21 int dir[6][3]= {{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
22 
23 bool ok(int x,int y,int z) {
24     if(x<0 || y<0 || z<0 || x>=l || y>=r || z>=c)
25         return 0;
26     else if(mapp[x][y][z] == '#')
27         return 0;
28     else if(vis[x][y][z])
29         return 0;
30     return 1;
31 }
32 int dfs() {
33     Node q,t;
34     queue<Node>Q;
35     q.f=s.f,q.r=s.r,q.c=s.c;
36     q.step=0;
37     vis[s.f][s.r][s.c]=1;
38     Q.push(q);
39     while(!Q.empty()) {
40         t=Q.front();
41         Q.pop();
42         Node a;
43         if(t.f==e.f&&t.r==e.r&&t.c==e.c) {
44             return t.step;
45         }
46         for(int i=0; i<6; i++) {
47             a.f=t.f+dir[i][0];
48             a.r=t.r+dir[i][1];
49             a.c=t.c+dir[i][2];
50             if(!ok(a.f,a.r,a.c))
51                 continue;
52             vis[a.f][a.r][a.c]=1;
53             a.step=t.step+1;
54             Q.push(a);
55         }
56     }
57     return 0;
58 }
59 int main() {
60     while(scanf("%d%d%d",&l,&r,&c),l||r||c) {
61         memset(vis,0,sizeof(vis));
62         for(int k=0; k<l; k++) {
63             for(int i=0; i<r; i++) {
64                     scanf("%s",mapp[k][i]);//遇到空格自动结束
65                 for(int j=0; j<c; j++) {
66                     //scanf("%c",mapp[k][i][j]);
67                     if(mapp[k][i][j]=='S') {
68                         s.f=k;
69                         s.r=i;
70                         s.c=j;
71                     }
72                     if(mapp[k][i][j]=='E') {
73                         e.f=k;
74                         e.r=i;
75                         e.c=j;
76                     }
77                 }
78             }
79         }
80         int ans;
81         ans=dfs();
82         if(ans)
83             printf("Escaped in %d minute(s).
",ans);
84         else
85             printf("Trapped!
");
86     }
87     return 0;
88 }
View Code
原文地址:https://www.cnblogs.com/ITUPC/p/5361516.html