三维BFS Poj 2251

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <iomanip>

using namespace std;
#define maxn 205

int d[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
typedef struct point
{
    int x,y,z;
    int ans;
}point;

point p[maxn];
int Map[33][33][33];
bool used[maxn][maxn][maxn];

int x1,x2,y2,z1,z2;
int you;//这里原本是想用y1的,但是在cmath这个函数中y1(y0,yn等)有自己的定义,发生了冲突(如果将cmath删掉,就可以定义了)
int BFS(int l,int n,int m)
{
    int ii,jj,zz;
    int i;
    queue<point>q;
    point temp1,temp2;
    temp1.x=x1;
    temp1.y=you;
    temp1.z=z1;
    temp1.ans=0;
    q.push(temp1);
    memset(used, false, sizeof(used));
           used[z1][x1][you]=true;
           while(!q.empty()){
               temp1=q.front();
               q.pop();
               for(i=0;i<6;i++)
               {
                   ii=temp1.x+d[i][0];
                   jj=temp1.y+d[i][1];
                   zz=temp1.z+d[i][2];
                   if(ii==x2 && jj==y2 && zz==z2)
                   {
                       return temp1.ans+1;
                   }
                   if(zz>=0 && zz<l && ii>=0 && ii<n && jj>=0 && jj<m && Map[zz][ii][jj]==1 && used[zz][ii][jj]==false)
                   {
                       used[zz][ii][jj]=true;
                       temp2.x=ii;
                       temp2.y=jj;
                       temp2.z=zz;
                       temp2.ans=temp1.ans+1;
                       q.push(temp2);
                   }
           }
               
     }
    return -1;
}
int main()
{
        int l,m,n,i,j,k,key;
        char str[40];
        while(cin>>l>>n>>m){
            if(l==0&&n==0&&m==0){
                break;
            }
            memset(Map, 0, sizeof(Map));
            for(k=0;k<l;k++){
                for(i=0;i<n;i++){
                    scanf("%s",str);
                    for(j=0;j<m;j++){
                        if(str[j]=='#')
                            Map[k][i][j]=0;
                        else if(str[j]=='.')
                        {
                            Map[k][i][j]=1;
                        }
                        else if(str[j]=='S')
                        {
                            z1=k;
                            x1=i;
                            you=j;
                        }
                        else
                        {
                            z2=k;
                            x2=i;
                            y2=j;
                        }
                    }
                }
            }
            key=BFS(l,n,m);
            if(key==-1)
                cout<<"Trapped!"<<endl;
            else
                printf("Escaped in %d minute(s).\n",key);
        }
        return 0;
}

 

posted @ 2018-08-10 14:15  小学弟-  阅读(229)  评论(0编辑  收藏  举报