POJ 2251 Dungeon Master bfs 难度:0

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

bfs,把两维换成三维,但是30*30*30=9e3的空间时间复杂度仍然足以承受

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
struct P{
        int x,y,z;
        P(){x=y=z=0;}
        P(int x,int y,int z){
                this->x=x;this->y=y;this->z=z;
        }
};
const int dx[6]={1,-1,0,0,0,0};
const int dy[6]={0,0,1,-1,0,0};
const int dz[6]={0,0,0,0,1,-1};

int l,r,c;
char maz[30][30][31];
int step[30][30][30];
bool in(int z,int x,int y){
        return z>=0&&z<l&&
        x>=0&&x<r&&
        y>=0&&y<c;
}
int main(){
        while(scanf("%d%d%d",&l,&r,&c)==3&&l){
                memset(step,0x7f,sizeof(step));
                for(int i=0;i<l;i++){
                        for(int j=0;j<r;j++){
                                scanf("%s",maz[i][j]);
                        }
                }
                queue<P> que;
                for(int i=0;i<l;i++){
                        for(int j=0;j<r;j++){
                                for(int k=0;k<c;k++){
                                        if(maz[i][j][k]=='E'){
                                                que.push(P(j,k,i));
                                                step[i][j][k]=0;
                                        }
                                }
                        }
                }
                bool fl=false;
                while(!que.empty()){
                        P f=que.front();que.pop();
                        int z=f.z,x=f.x,y=f.y;
                        if(maz[z][x][y]=='S'){
                                fl=true;
                                printf("Escaped in %d minute(s).
",step[z][x][y]);
                                break;
                        }
                        for(int i=0;i<6;i++){
                                int tx=x+dx[i],ty=y+dy[i],tz=z+dz[i];
                                if(in(tz,tx,ty)&&maz[tz][tx][ty]!='#'&&step[tz][tx][ty]>step[z][x][y]+1){
                                        step[tz][tx][ty]=step[z][x][y]+1;
                                        que.push(P(tx,ty,tz));
                                }
                        }
                }
                while(!que.empty())que.pop();
                if(!fl)puts("Trapped!");
        }
        return 0;
}

  

原文地址:https://www.cnblogs.com/xuesu/p/4337433.html