poj 2251 Dungeon Master (BFS)

题目链接:http://poj.org/problem?id=2251

题意:在一个地体空间,有L个平面,每个平面R行C列,寻找从S到E的最短时间,有六个方向(上下东南西北)行走;若不能到达E,输出 "Trapped!",‘.'代表路,‘#’代表墙壁。

题解:一道简单的BFS,只要对图遍历一遍就能出结果,具体步骤看代码。

#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;

struct point
{
    int z,x,y,cou;
};//记录每个点的位置及从起始点到达这里的时间
queue<point>p;
char map[35][35][35];
int l,r,c;
int go[6][3]={0,0,1,0,0,-1,0,1,0,0,-1,0,1,0,0,-1,0,0};//六个方向

int bfs()
{
    while(!p.empty())
    {
        point temp;
        temp=p.front();
        p.pop();

        for(int i=0;i<6;i++)
        {
            int Z=temp.z+go[i][0];
            int X=temp.x+go[i][1];
            int Y=temp.y+go[i][2];
            if(Z>=l || Z<0 || X>=r || X<0 || Y>=c || Y<0)
                continue;
            if(map[Z][X][Y]=='E')
                return temp.cou+1;
            if(map[Z][X][Y]=='.')
            {
                point q;
                q.z=Z;
                q.x=X;
                q.y=Y;
                q.cou=temp.cou+1;
                p.push(q);
                map[Z][X][Y]='#';//对走过的路进行标记,直接变为墙,以免再次遍历
            }
        }
    }
    return 0;
}
int main()
{
    while(cin>>l>>r>>c)
    {
        if(l==0) break;
        while(!p.empty())
            p.pop();
        for(int i=0;i<l;i++)
            for(int j=0;j<r;j++)
                scanf("%s",map[i][j]);
        for(int i=0;i<l;i++)
            for(int j=0;j<r;j++)
                for(int k=0;k<c;k++)
                {
                    if(map[i][j][k]=='S')
                    {
                        point temp;
                        temp.z=i;
                        temp.x=j;
                        temp.y=k;
                        temp.cou=0;
                        p.push(temp);
                    }
                }
        int t=bfs();
        if(t) printf("Escaped in %d minute(s).\n",t);
        else printf("Trapped!\n");
    }
    return 0;
}

 

posted on 2015-04-22 10:44  猫哥小俊  阅读(170)  评论(0编辑  收藏  举报

导航