どこでもドア:http://poj.org/problem?id=2251
三维迷宫,L表示层数。’#’是墙,输出从S到E最少步数
AC CODE:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<sstream>
#include<set>
#include<cstdlib>
#include<map>
#include<queue>
using namespace std;
const int M=32;
typedef struct point
{
int z,x,y;
int step;
}PO;
char ma[M][M][M];
int L,R,C ,ans;
int vis[M][M][M];
int dir[6][3]={0,0,1 ,0,1,0 ,0,0,-1 ,0,-1,0 ,1,0,0 ,-1,0,0 };//三维的有6个方向上下左右前后
PO st,N,I;
bool check(int z,int x,int y) //判断是否能向这个点移动
{
if(x>=0&&y>=0&&z>=0&&z<L&&x<R&&y<C&&ma[z][x][y]!='#'&&!vis[z][x][y])
return 1;
return 0;
}
int BFS()
{
vis[st.z][st.x][st.y] = 1;
queue <PO> Q;
Q.push(st);
while(!Q.empty())
{
N = Q.front();
Q.pop();
for(int i = 0; i < 6; i++)
{
I.z = N.z+dir[i][0];
I.x = N.x+dir[i][1];
I.y = N.y+dir[i][2];
I.step=N.step+1;
if(check(I.z,I.x, I.y))
{
vis[I.z][I.x][I.y] = 1;
if(ma[I.z][I.x][I.y]=='E') //如果到了终点,返回step
return I.step;
Q.push(I);
}
}
}
return 0;
}
int main()
{
while(cin>>L>>R>>C)
{
memset(vis,0,sizeof(vis));
if(L==0&&R==0&&C==0)
break;
for(int i=0;i<L;i++)
for(int j=0;j<R;j++)
for(int k=0;k<C;k++)
{
cin>>ma[i][j][k];
if(ma[i][j][k]=='S')
{
st.z=i;
st.x=j;
st.y=k;
st.step=0;
}
}
ans=BFS();
if(ans)
cout<<"Escaped in "<<ans<<" minute(s)."<<endl;
else
cout<<"Trapped!"<<endl;
}
return 0;
}
PS:遇到MLE,在循环和递归中定义变量可能会有影响。