http://poj.org/problem?id=2251
(1)简单题,注意用 flag 标记是否有解。
(2)写时没有将第一个元素入队,导致均无解。。
具体代码:

#include<stdio.h> #include<string.h> #include<queue> using namespace std; int n, m, l; char map[35][35][35]; int mark[35][35][35]; int px, py, pz; int dir[6][3]={1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1}; int flag; struct node { int x, y, z, step; }e, s; int yes(int x, int y, int z) { return x>=0&&x<n&&y>=0&&y<m&&z>=0&&z<l&&map[x][y][z]!='#'&&!mark[x][y][z]; } void bfs() { int i, j, k; memset(mark, 0, sizeof(mark)); mark[px][py][pz]=1; queue<node>q; while(!q.empty()) q.pop(); e.x=px, e.y=py, e.z=pz, e.step=0; q.push(e); while(!q.empty()) { e=q.front(); q.pop(); if(map[e.x][e.y][e.z]=='E') {flag=1;break;} for(i=0;i<6;i++) { s.x=e.x+dir[i][0]; s.y=e.y+dir[i][1]; s.z=e.z+dir[i][2]; s.step=e.step+1; if(!yes(s.x, s.y, s.z)) continue; q.push(s); mark[s.x][s.y][s.z]=1; } } if(flag) printf("Escaped in %d minute(s).\n", e.step); else printf("Trapped!\n"); } int main() { int i, j, k; while(scanf("%d%d%d", &n, &m, &l)!=EOF, n||m||l) { for(i=0;i<n;i++) for(j=0;j<m;j++) scanf("%s", map[i][j]); for(i=0;i<n;i++) for(j=0;j<m;j++) for(k=0;k<l;k++) if(map[i][j][k]=='S') px=i, py=j, pz=k; flag=0; bfs(); } return 0; }