http://poj.org/problem?id=2251
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 18773 | Accepted: 7285 |
Description
Input
Output
Escaped in x minute(s).
Trapped!
Sample Input
3 4 5
S....
.###.
.##..
###.#
#####
#####
##.##
##...
#####
#####
#.###
####E
1 3 3
S##
#E#
###
0 0 0
Sample Output
Escaped in 11 minute(s). Trapped!
分析:
典型的三维广搜。
AC代码:
1 #include<cstdio>
2 #include<cstring>
3 #include<queue>
4 using namespace std; 5
6 #define INF 0x3f3f3f3f
7
8 char maz[31][31][31]; 9 int d[31][31][31]; 10 int sx,sy,sz; 11 int ex,ey,ez; 12 int dx[6] = {1,-1,0,0,0,0}; 13 int dy[6] = {0,0,1,-1,0,0}; 14 int dz[6] = {0,0,0,0,1,-1}; 15 int X,Y,Z; 16 struct P{ 17 int x,y,z; 18 P(int xx,int yy,int zz) :x(xx),y(yy),z(zz) { 19 } 20 }; 21
22 int bfs() { 23 memset(d,INF,sizeof(d)); 24 queue<P> que; 25 que.push(P(sx,sy,sz)); 26 d[sx][sy][sz] = 0; 27
28
29 while(que.size()) { 30 P p = que.front();que.pop(); 31
32 if(p.x == ex && p.y == ey && p.z == ez) break; 33
34 for(int i = 0;i < 6;i++) { 35 int nx = p.x + dx[i]; 36 int ny = p.y + dy[i]; 37 int nz = p.z + dz[i]; 38
39 if(0 <= nx && nx < X && 0 <= ny && ny < Y && 0 <= nz && nz < Z 40 && maz[nx][ny][nz] != '#' && d[nx][ny][nz] == INF) { 41 que.push(P(nx,ny,nz)); 42 d[nx][ny][nz] = d[p.x][p.y][p.z] + 1; 43 } 44 } 45 } 46 if(d[ex][ey][ez] == INF) return -1; 47 return d[ex][ey][ez]; 48 } 49
50 int main() { 51 while(~scanf("%d %d %d",&X,&Y,&Z)) { 52 if(X == 0 && Y == 0 && Z == 0) break; 53 for(int i = 0;i < X;i++) { 54 for(int j = 0;j < Y;j++) { 55 scanf("%s",maz[i][j]); 56 for(int k = 0;k < Z;k++) { 57 if(maz[i][j][k] == 'S') { 58 sx = i; 59 sy = j; 60 sz = k; 61 } else if(maz[i][j][k] == 'E') { 62 ex = i; 63 ey = j; 64 ez = k; 65 } 66 } 67 } 68 } 69
70
71 int res = bfs(); 72 if(res == -1) { 73 printf("Trapped!\n"); 74 } else { 75 printf("Escaped in %d minute(s).\n",res); 76 } 77 } 78 return 0; 79 }