POJ 2251 Dungeon Master

来源:互联网 发布:神仙道 源码 编辑:程序博客网 时间:2024/06/02 01:39

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

题目的要求很简单,就是求个最短路

只不过二维的迷宫推广到了三维的迷宫而已

就是用BFS用到队列

话不多说,直接上代码,很好理解.

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#include <stack>#include <queue>using namespace std;int m,n,p;int sx,sy,sz,ex,ey,ez;char map[31][31][31];bool vis[31][31][31];int dir[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};//三维方向struct node{    int x;    int y;    int z;    int t;}now,next;bool check(int x,int y,int z){    if(x>=0&&x<n&&y>=0&&y<m&&z>=0&&z<p)    {        return true;    }    return false;}int bfs(){    int fx,fy,fz;    queue<node> q;    now.x=sx;    now.y=sy;    now.z=sz;    now.t=0;    q.push(now);//把当前的位置压入队列    while(!q.empty())    {        now=q.front();        q.pop();        if(now.x==ex&&now.y==ey&&now.z==ez)        {            return now.t;        }        for(int i=0;i<6;i++)        {            fx=now.x+dir[i][0];            fy=now.y+dir[i][1];            fz=now.z+dir[i][2];            if(check(fx,fy,fz)&&map[fx][fy][fz]!='#'&&!vis[fx][fy][fz])            {                vis[fx][fy][fz]=true;                next.x=fx;                next.y=fy;                next.z=fz;                next.t=now.t+1;                q.push(next);//把接下来的步骤压入队列            }        }    }    return 0;}int main(){    int time;    //freopen("in.txt","r",stdin);    while(scanf("%d%d%d",&p,&n,&m)!=EOF)    {        if(p==0&&m==0&&n==0)            break;        getchar();        memset(vis,0,sizeof vis);        for(int i=0;i<p;i++)        {            for(int j=0;j<n;j++)            {                for(int k=0;k<m;k++)                {                    cin>>map[j][k][i];                    if(map[j][k][i]=='S')                    {                        sx=j;                        sy=k;                        sz=i;                        map[j][k][i]='#';                    }                    else if(map[j][k][i]=='E')                    {                        ex=j;                        ey=k;                        ez=i;                    }                }            }        }        time=bfs();        if(time==0)        {            cout<<"Trapped!"<<endl;        }        else        {            cout<<"Escaped in "<<time<<" minute(s)."<<endl;        }    }    return 0;}


0 0