pku 2251 Dungeon Master BFS

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

很简单的求最短路径的BFS题目,才开始自己写了各DFS直接性TLE。。。

三维的,就是多加了两个方向罢了,再处理的时候就按i,j,k来;

View Code
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#define maxn 33
using namespace std;

struct node
{
    int x,y,z;
    int len;
}s;
char map[maxn][maxn][maxn];
bool vt[maxn][maxn][maxn];
int l,r,c,ans;
bool flag;
int dir[6][3] = {{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
int bfs()
{
    int i;
    node t;
    queue<node>q;
    while (!q.empty()) q.pop();
    q.push(s);
    vt[s.x][s.y][s.z] = true;
    while (!q.empty())
    {
        node cur = q.front();
        q.pop();
        if (map[cur.x][cur.y][cur.z] == 'E')
        {
            return cur.len;
        }
        for (i = 0; i < 6; ++i)
        {
            t.x = cur.x + dir[i][0];
            t.y = cur.y + dir[i][1];
            t.z = cur.z + dir[i][2];
            if (t.x >= 0 && t.x < l && t.y >= 0 &&t.y < r && t.z >= 0 && t.z < c && map[t.x][t.y][t.z] != '#' && !vt[t.x][t.y][t.z])
            {
                vt[t.x][t.y][t.z] = true;
                t.len = cur.len + 1;
                q.push(t);
            }
        }
    }
    return -1;
}
int main()
{
    //freopen("in.txt","r",stdin);
    int i,j,k;
    while (scanf("%d%d%d",&l,&r,&c))
    {
        if (!l && ! r && !c) break;
        for (i = 0; i < l; ++i)
        {
            for (j = 0; j < r; ++j)
            {
                scanf("%s",map[i][j]);
                for (k = 0; k < c; ++k)
                {
                    if (map[i][j][k] == 'S')
                    {
                        s.x = i; s.y = j;
                        s.z = k; s.len = 0;
                    }
                }
            }
        }
        memset(vt,false,sizeof(vt));
        int l = bfs();
        if (l == -1)
        printf("Trapped!\n");
        else
        printf("Escaped in %d minute(s).\n",l);
    }
    return 0;
}

 

posted @ 2012-04-13 20:30  E_star  阅读(209)  评论(0编辑  收藏  举报