zoukankan      html  css  js  c++  java
  • 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).
    ",t);
            else printf("Trapped!
    ");
        }
        return 0;
    }
  • 相关阅读:
    虚继承virtual public
    My first blog
    mybatis(一)SqlSessionFactory初始化
    dubbo
    设计模式
    基本算法
    redis
    spring cloud eureka
    spring boot
    spring MVC
  • 原文地址:https://www.cnblogs.com/mgxj/p/4446720.html
Copyright © 2011-2022 走看看