C - Dungeon Master (第一道queue实现的BFS)

#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
char a[35][35][35];
int vis[35][35][35];
int ob[6][3]={{-1,0,0},{1,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1}};
int l,r,c,sx,sy,sz,ex,ey,ez,n;
struct node
{
int x,y,z,step;
};
bool check(int x,int y,int z)
{
if(x<0||y<0||z<0||x>=l||y>=r||z>=c)
return 1;
else if(a[x][y][z]=='#')
return 1;
else if(vis[x][y][z]==1)
return 1;
return 0;

}
int bfs()
{
int i;
node a,next;
queue<node> Q;
a.x=sx;a.y=sy;a.z=sz;
a.step=0;
vis[sx][sy][sz] = 1;
Q.push(a);
while(!Q.empty())
{
a=Q.front();
Q.pop();
if(a.x==ex&&a.y==ey&&a.z==ez)
return a.step;
for(i=0;i<6;i++)
{
next=a;
next.x=a.x+ob[i][0];
next.y=a.y+ob[i][1];
next.z=a.z+ob[i][2];
if(check(next.x,next.y,next.z))
continue;
vis[next.x][next.y][next.z]=1;
next.step = a.step+1;
Q.push(next);
}
}
return 0;
}
int main()
{
int i,j,k,ans;
while(scanf("%d%d%d",&l,&r,&c),l+r+c)
{
memset(a,0,sizeof(a));
memset(vis,0,sizeof(vis));
for(i=0;i<l;i++)
{
for(j=0;j<r;j++)
{
scanf("%s",&a[i][j]);
for(k=0;k<c;k++)
{
if(a[i][j][k]=='S')
{
sx=i;sy=j;sz=k;
}
if(a[i][j][k]=='E')
{
ex=i;ey=j;ez=k;
}
}
}
}
ans=0;
ans=bfs();
if(ans)
printf("Escaped in %d minute(s).\n",ans);
else
printf("Trapped!\n");

}
}

猜你喜欢

转载自www.cnblogs.com/guanwen769aaaa/p/9984822.html
今日推荐