POJ 2251 (BFS)

很典型的一种BFS裸题。
直接怼就行

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<cmath>
#include<cstdlib>
#include<list>
#include<queue>
#define mm(a,b) memset(a,b,sizeof(a))
#define ACCELERATE (ios::sync_with_stdio(false),cin.tie(0))
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
using namespace std;

char mmp[35][35][35];

struct node{
    int x;
    int y;
    int z;
    int step;
    node(int a,int b,int c,int d):x(a),y(b),z(c),step(d){}
};

queue<node> q;
int sx,sy,sz;
int ex,ey,ez;
int x,y,z;

int tmp[6][3]={
    {0,1,0},
    {0,-1,0},
    {0,0,1},
    {0,0,-1},
    {1,0,0},
    {-1,0,0}
};

inline int judge(int a,int b,int c){
    if(a>=0&&b>=0&&c>=0&&a<x&&b<y&&c<z&&mmp[a][b][c]!='#') return 1;
    return 0;
}

int bfs(){
    while(!q.empty()){
        node t=q.front();
        q.pop();
        if(t.x==ex&&t.y==ey&&t.z==ez){
            return t.step;
        }
        for(int i=0;i<6;i++){
            for(int j=0;j<3;j++){
                if(judge(t.x+tmp[i][0],t.y+tmp[i][1],t.z+tmp[i][2])){
                    q.push(node(t.x+tmp[i][0],t.y+tmp[i][1],t.z+tmp[i][2],t.step+1));
                    mmp[t.x+tmp[i][0]][t.y+tmp[i][1]][t.z+tmp[i][2]]='#';
                }
            }
        }
    }
    return 0;
}

int main()
{
    while(scanf("%d%d%d",&x,&y,&z)!=EOF&&(x||y||z)){
        for(int i=0;i<x;i++){
            for(int j=0;j<y;j++){
                for(int k=0;k<z;k++){
                    char ch;
                    scanf("%c",&ch);
                    while(ch=='\n') scanf("%c",&ch);
                    mmp[i][j][k]=ch;
                    if(mmp[i][j][k]=='S'){
                        sx=i;sy=j;sz=k;
                    }if(mmp[i][j][k]=='E'){
                        ex=i;ey=j;ez=k;
                    }
                }
            }
        }
        while(!q.empty()){
            q.pop();
        }
        q.push(node(sx,sy,sz,0));
        int ans=bfs();
        if(ans==0) puts("Trapped!");
        else{
            printf("Escaped in %d minute(s).\n",ans);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40679299/article/details/80690129