POJ - 2251 Dungeon Master (三维bfs)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuxiyulu/article/details/77983718
/*
三维bfs
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn=30+5;
int L,R,C;
char mp[maxn][maxn][maxn];
bool vis[maxn][maxn][maxn];
int sx,sy,sz,ex,ey,ez;//起点、终点
int dis[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
//6个方向(东南西北上下)
struct node
{
    int x,y,z;
    int step;
};
bool check(int x,int y,int z)
{
    if(x<0||y<0||z<0||x>=L||y>=R||z>=C)
        return 0;
    else if(mp[x][y][z]=='#')
        return 0;
    else if(vis[x][y][z])
        return 0;
    return 1;
}

int bfs()
{
    node work,next;
    queue<node>qu;
    work.x=sx;
    work.y=sy;
    work.z=sz;
    work.step=0;
    vis[sx][sy][sz]=1;//标记已走过的
    qu.push(work);
    while(!qu.empty())
    {
        work=qu.front();
        qu.pop();
        if(work.x==ex&&work.y==ey&&work.z==ez)
            return work.step;
        for(int i=0;i<6;i++)//枚举6个方向
        {
            next.x=work.x+dis[i][0];
            next.y=work.y+dis[i][1];
            next.z=work.z+dis[i][2];
            if(check(next.x,next.y,next.z))//下一步合法
            {
                vis[next.x][next.y][next.z]=1;
                next.step=work.step+1;
                qu.push(next);
            }
        }
    }
    return 0;
}

int main()
{
    while(~scanf("%d%d%d",&L,&R,&C))
    {
        if(L==0&&R==0&&C==0) break;

        for(int i=0;i<L;i++)
        {
            for(int j=0;j<R;j++)
            {
                scanf("%s",mp[i][j]);
                for(int k=0;k<C;k++)
                {
                    if(mp[i][j][k]=='S')
                    {
                        sx=i;
                        sy=j;
                        sz=k;
                    }
                    if(mp[i][j][k]=='E')
                    {
                        ex=i;
                        ey=j;
                        ez=k;
                    }
                }
            }
        }
        memset(vis,0,sizeof(vis));
        int ans=bfs();
        //printf("%d\n",ans);
        if(ans)
        {
            printf("Escaped in %d minute(s).\n",ans);
        }
        else
        {
            printf("Trapped!\n");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhuxiyulu/article/details/77983718
今日推荐