题目链接:http://poj.org/problem?id=2251
解析:
简单的三维BFS问题。
代码:
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <set> #include <map> using namespace std; #define Lowbit(x) ((x)&(-(x))) #define ll long long #define mp make_pair #define ff first #define ss second #define pb push_back #define mod 10000007 //#define LOCAL #define MAXN 100010 #define INF 1e9 #define Max 100010 int tx[]={0,0,0,0,1,-1}; int ty[]={1,0,-1,0,0,0}; int tz[]={0,1,0,-1,0,0}; char str[35][35][35]; bool visit[35][35][35]; typedef struct node{ int x,y,z; int cost; }NODE; int L,R,C; bool check(int x,int y,int z){ if(x<0||x>=L||y<0||y>=R||z<0||z>=C||visit[x][y][z]||str[x][y][z]!='.') return false; visit[x][y][z] = true; return true; } int main(){ while(~scanf("%d%d%d", &L,&R,&C),L||R||C){ int i,j,k; for(i=0; i<L; ++i){ for(j=0; j<R; ++j){ scanf("%s", str[i][j]); } } NODE now,tar; for(i=0; i<L; ++i){ for(j=0; j<R; ++j){ for(k=0; k<C; ++k){ if(str[i][j][k]=='S'){ now.x = i; now.y = j; now.z = k; str[i][j][k]='.'; } else if(str[i][j][k]=='E'){ tar.x = i; tar.y = j; tar.z = k; str[i][j][k]='.'; } } } } //BFS memset(visit,false,sizeof(visit)); queue<NODE> que; now.cost = 0; que.push(now); visit[now.x][now.y][now.z] = true; int ans = -1; while(que.size()){ now = que.front(); que.pop(); if(now.x==tar.x&&now.y==tar.y&&now.z==tar.z){ ans = now.cost; break; } for(i=0; i<6; ++i){ NODE tmp; tmp.x = now.x+tx[i]; tmp.y = now.y+ty[i]; tmp.z = now.z+tz[i]; tmp.cost = now.cost+1; if(check(tmp.x,tmp.y,tmp.z)){ que.push(tmp); } } } if(-1==ans) printf("Trapped! "); else printf("Escaped in %d minute(s). ", ans); } return 0; }