POJ2251 Dungeon Master(bfs)

题目链接

题目大意:

三维迷宫,搜索从s到e的最小步骤数。

分析:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <cstring>
#include <queue>

using namespace std;

const int maxn = 35;

int dx[] = {0, 0, -1, 1, 0, 0};
int dy[] = {0, 0, 0, 0, -1, 1};
int dz[] = {-1, 1, 0, 0, 0, 0};

char G[maxn][maxn][maxn];
bool vis[maxn][maxn][maxn];
int r, l, c;

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

int BFS(int x0, int y0, int z0) {
    queue<Pos> Q;

    Q.push((Pos){x0, y0, z0, 0});

    while(!Q.empty()) {
        Pos e = Q.front(); Q.pop();
        int x=e.x, y=e.y, z=e.z, s=e.step;

        if(G[z][x][y] == 'E') return s;

        for(int d=0; d<6; d++) {
            int nx, ny, nz;
            nx = x+dx[d];
            ny = y+dy[d];
            nz = z+dz[d];

            if(nx < 0 || ny < 0 || nz < 0) continue;
            if(nx >= r || ny >= c || nz >= l) continue;
            if(vis[nz][nx][ny]) continue;
            if(G[nz][nx][ny] == '#') continue;

            vis[nz][nx][ny] = true;

            Q.push((Pos){nx, ny, nz, s+1});
        }
    }

    return -1;
}

int main() {
    int x0, y0, z0;

    while(scanf("%d%d%d", &l, &r, &c) == 3) {
        if(l == 0 && r == 0 && c == 0) break;

        for(int i=0; i<l; i++) {
            for(int j=0; j<r; j++) {
                scanf("%s", G[i][j]);
            }
        }

        for(int i=0; i<l; i++) {
            for(int j=0; j<r; j++) {
                for(int k=0; k<c; k++) {
                    if(G[i][j][k] == 'S'){
                        z0 = i; x0=j; y0=k;
                    }
                }
            }
        }

        memset(vis, false, sizeof(vis));

        int res = BFS(x0, y0, z0);
        
        if(res == -1) {
            printf("Trapped!\n");
        }
        else
            printf("Escaped in %d minute(s).\n", res);
    }

    return 0;
}

 

posted on 2013-07-31 16:53  Still_Raining  阅读(157)  评论(0编辑  收藏  举报