poj 2251 Dungeon Master(广搜)

题意:三维空间,可以走上下左右前后六个方向,求最短路径,BFS

  

#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
const int MAXN=50;

char str[MAXN][MAXN][MAXN];
int step[MAXN][MAXN][MAXN];
int vis[MAXN][MAXN][MAXN];
int l,r,c;
struct Node
{
    int x,y,z;
}s,e;

int BFS()
{
    int i,j;
    Node head,next;
    queue<Node>Q;
    Q.push(s);
    step[s.x][s.y][s.z]=0;
    while(!Q.empty())
    {
        head=Q.front();
        Q.pop();
        for(i=0;i<6;i++)
        {
            next=head;
            if(i==0) next.x-=1;
            if(i==1) next.x+=1;
            if(i==2) next.y-=1;
            if(i==3) next.y+=1;
            if(i==4) next.z-=1;
            if(i==5) next.z+=1;
            if(!vis[next.x][next.y][next.z] && str[next.x][next.y][next.z]==1)
            {
                vis[next.x][next.y][next.z]=1;
                Q.push(next);
                step[next.x][next.y][next.z]=step[head.x][head.y][head.z]+1;
                if(next.x==e.x && next.y==e.y && next.z==e.z) return  step[head.x][head.y][head.z]+1;
            }
        }
    }
    return  0;
}
int main()
{
    int i,j,k;
    while(scanf("%d%d%d",&l,&r,&c)!=EOF)
    {
        if(l==0 && r==0 && c==0) break;
        memset(vis,0,sizeof(vis));
        memset(str,0,sizeof(str));
        for(i=1; i<=l; i++)
        {
            for(j=1; j<=r; j++)
            {
                scanf("%s",str[i][j]+1);
                for(k=1; str[i][j][k]; k++)
                {
                    if(str[i][j][k]=='#') str[i][j][k]=0;
                    if(str[i][j][k]=='.') str[i][j][k]=1;
                    if(str[i][j][k]=='S')
                    {
                        str[i][j][k]=1;
                        s.x=i;
                        s.y=j;
                        s.z=k;
                    }
                    if(str[i][j][k]=='E')
                    {
                        str[i][j][k]=1;
                        e.x=i;
                        e.y=j;
                        e.z=k;
                    }
                }
            }
        }
        int ans=BFS();
        if(ans) printf("Escaped in %d minute(s).\n",ans);
        else printf("Trapped!\n");

    }
    return 0;
}

 

posted @ 2013-02-05 13:53  calmound  阅读(168)  评论(0编辑  收藏  举报