做题时需要注意,爬楼有向上和向下爬之分...
本题大意:输入 l, r, c, 分别代表地牢的楼层数和每层地牢的长和宽,地牢由rock and point and source and key组成,你初始在s位置,你只能向身边的四个方向和上下方向移动,问你是否能走出地牢,能的话求出最短路径。
本题思路:BFS爆搜就OK,我不喜欢存运动方向,所以用循环判断了,按道理循环较慢...所以根据读者喜好选择...
参考代码:
1 #include <cstdio> 2 #include <iostream> 3 #include <queue> 4 #include <cmath> 5 #include <cstring> 6 using namespace std; 7 8 struct node { 9 int x, y, z, step; 10 } now, Next, source, key; 11 const int maxn = 30 + 5; 12 int l, r, c, ans; 13 char dungeon[maxn][maxn][maxn]; 14 bool vis[maxn][maxn][maxn]; 15 16 int bfs() { 17 memset(vis, false, sizeof vis); 18 source.step = 0; 19 vis[source.x][source.y][source.z] = true; 20 queue <node> Q; 21 Q.push(source); 22 while(!Q.empty()) { 23 now = Q.front(); 24 Q.pop(); 25 if(now.x == key.x && now.y == key.y && now.z == key.z) return now.step; 26 Next.step = now.step + 1; 27 for(int i = -1; i <= 1; i ++) 28 if(i != 0) { 29 Next.x = now.x + i, Next.y = now.y, Next.z = now.z; 30 if(Next.x >= 0 && Next.y >= 0 && Next.z >= 0 && Next.x < l && Next.y < r && Next.z < c && !vis[Next.x][Next.y][Next.z] && dungeon[Next.x][Next.y][Next.z] != '#' ) { 31 Next.step = now.step + 1; 32 vis[Next.x][Next.y][Next.z] = true; 33 Q.push(Next); 34 } 35 } 36 for(int dy = -1; dy <= 1; dy ++) { 37 for(int dz = -1; dz <= 1; dz ++) { 38 if((int)(abs(dy - dz)) == 1) { 39 Next.x = now.x + 0, Next.y = now.y + dy, Next.z = now.z + dz; 40 if(Next.x >= 0 && Next.y >= 0 && Next.z >= 0 && Next.x < l && Next.y < r && Next.z < c && !vis[Next.x][Next.y][Next.z] && dungeon[Next.x][Next.y][Next.z] != '#') { 41 vis[Next.x][Next.y][Next.z] = true; 42 Q.push(Next); 43 } 44 } 45 } 46 } 47 } 48 return -1; 49 } 50 51 int main () { 52 while(~scanf("%d %d %d", &l, &r, &c)) { 53 if(l == 0 && r == 0 && c == 0) break; 54 for(int i = 0; i < l; i ++) { 55 for(int j = 0; j < r; j ++) { 56 for(int k = 0; k < c; k ++) { 57 cin >> dungeon[i][j][k]; 58 if(dungeon[i][j][k] == 'S') { source.x = i; source.y = j; source.z = k; } 59 if(dungeon[i][j][k] == 'E') { key.x = i; key.y = j; key.z = k; } 60 } 61 } 62 } 63 ans = bfs(); 64 if(ans != -1) printf("Escaped in %d minute(s). ", ans); 65 else printf("Trapped! "); 66 } 67 return 0; 68 }