Dungeon Master(POJ2251)(C)

どこでもドア: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,在循环和递归中定义变量可能会有影响。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值