POJ 2251 Dungeon Master 三維BFS

注意x,y,z的方向,簡單的BFS
#include <algorithm>
#include <iostream>
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;

struct node
{
    int x, y, z;
    int step;
};

int x,y,z,sx,sy,sz,ex,ey,ez;
char map[40][40][40];
int book[40][40][40];
int dx[] = {1,-1,0,0,0,0};
int dy[] = {0,0,1,-1,0,0};
int dz[] = {0,0,0,0,1,-1};

int check(node a)
{
    if(a.x>=0&&a.x<x&&a.y>=0&&a.y<y&&a.z>=0&&a.z<z&&!book[a.x][a.y][a.z]&&map[a.x][a.y][a.z]!='#')
        return 1;
    else
        return 0;
}
int BFS()
{
    queue<node>Q;
    node a, next,q;
    a.x = sx;
    a.y = sy;
    a.z = sz;
    book[sx][sy][sz] = 1;
    a.step = 0;
    Q.push(a);
    while(!Q.empty()){
        q = Q.front();
        Q.pop();
         if(q.x==ex&&q.y==ey&&q.z==ez){
            return q.step;
         }
         for(int i = 0;i < 6;i++){
            next.x = q.x+dx[i];
            next.y = q.y+dy[i];
            next.z = q.z+dz[i];
            if(check(next)){
                book[next.x][next.y][next.z] = 1;
                next.step = q.step+1;
                Q.push(next);
            }
         }
    }
    return -1;
}
int main()
{
    while(~scanf("%d %d %d", &x, &y, &z)){
        if(x==0&&y==0&&z==0)    break;
        for(int i = 0;i < x;i++){
            for(int j = 0;j < y;j++){
                scanf("%s", map[i][j]);
                for(int k = 0;k < z;k++){
                    if(map[i][j][k] == 'S'){
                        sx = i;
                        sy = j;
                        sz = k;
                    }else if(map[i][j][k] == 'E'){
                        ex = i;
                        ey = j;
                        ez = k;
                    }
                }
            }
        }
        memset(book,0,sizeof(book));
        int t = BFS();
        if(t == -1){
            printf("Trapped!\n");
        }else {
            printf("Escaped in %d minute(s).\n", t);
        }
    }

    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章