poj 2251
三维的dfs。
#include <iostream> #include <cstring> using namespace std; struct q { int x; int y; int z; }q[30000]; int length[30000]; int xx[]={1,-1,0,0,0,0}; int yy[]={0,0,0,0,-1,1}; int zz[]={0,0,-1,1,0,0}; bool dis[40][40][40]; char map[40][40][40]; int l,r,c,sx,sy,sz; int bfs() { int rear, front, dx, dy, dz, i; memset(dis, false, sizeof(dis)); memset(length, 0, sizeof(length)); q[0].x = sx; q[0].y = sy; q[0].z = sz; front = rear = 0; while(front <= rear) { for(i=0; i<6; i++) { dx = q[front].x + xx[i]; dy = q[front].y + yy[i]; dz = q[front].z + zz[i]; if(!dis[dx][dy][dz] && (map[dx][dy][dz]=='.' || map[dx][dy][dz]=='E') && dx>=0 && dx<l && dy>=0 && dy<r && dz>=0 && dz<c) { dis[dx][dy][dz] = true; q[++rear].x = dx; q[rear].y = dy; q[rear].z = dz; length[rear] = length[front] + 1; if(map[dx][dy][dz] == 'E') return length[rear]; } } front++; } return 0; } int main() { int i, j, k, key; while(~scanf("%d%d%d\n", &l, &r, &c)) { if(l==0 && r==0 && c==0) break; for(i=0; i<l; i++,getchar()) for(j=0; j<r; j++,getchar()) for(k=0; k<c; k++) { scanf("%c", &map[i][j][k]); if(map[i][j][k] == 'S') sx=i, sy=j, sz=k; } key = bfs(); if(key) printf("Escaped in %d minute(s).\n",key); else printf("Trapped!\n"); } return 0; }