IT民工
加油!

这道题本来不难,但是写的纠结。三维广搜,只有六个方向,有一段时间没写结构体,发现很不熟练。

/*Accepted    612K    16MS    C++    2362B    2012-07-23 17:48:55*/
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
using namespace std;

const int MAXN = 50;
const int dx[] = { 1, -1, 0, 0, 0, 0};
const int dy[] = { 0, 0, 1, -1, 0, 0};
const int dz[] = { 0, 0, 0, 0, 1, -1};
int H, R, C;

struct Node
{
    int x, y, z;
    int steps;
};

Node S, E;

char a[MAXN][MAXN][MAXN];
int map[MAXN][MAXN][MAXN];

bool judge( int x, int max)
{
    if( x > 0 && x <= max)
        return true;
    return false;
}

void init()
{
    int i, j, k;
    for( k = 1; k <= H; k ++)
    {
        for( i = 1; i <= R; i ++)
        {
            scanf( "%s", a[k][i] + 1);
            for( j = 1; j <= C; j ++)
            {
                if( a[k][i][j] == '#')
                    map[k][i][j] = 0;
                else  map[k][i][j] = 1;
                if( a[k][i][j] == 'S')
                {
                    S.z = k;
                    S.x = i;
                    S.y = j;
                }
                if( a[k][i][j] == 'E')
                {
                    E.z = k;
                    E.x = i;
                    E.y = j;
                    E.steps = -1;
                }
            }
        }
    }
}

void bfs()
{
    int i;
    Node p1, p2;
    queue<Node> q;
    S.steps = 0;
    q.push(S);
    while( !q.empty())
    {
        p1 = q.front(); q.pop();
        if( p1.z == E.z && p1.x == E.x && p1.y == E.y) break;
        for( i = 0; i < 6; i ++)
        {
            p2.x = p1.x + dx[i];
            p2.y = p1.y + dy[i];
            p2.z = p1.z + dz[i];
            if( map[p2.z][p2.x][p2.y] == 1 && judge(p2.z, H) && judge(p2.x, R) && judge(p2.y, C))
            {
                map[p2.z][p2.x][p2.y] = 0;
                p2.steps = p1.steps + 1;
                q.push(p2);
                if( p2.z == E.z && p2.x == E.x && p2.y == E.y){
                    E.steps = p2.steps;
                    return;
                }
            }
        }
    }
}

int main()
{
    while( scanf( "%d%d%d", &H, &R, &C) != EOF)
    {

        if( H == 0 && R == 0 && C == 0) break;
        init();
        bfs();
        if( E.steps < 0)
        {
            printf( "Trapped!\n");
        }
        else
            printf( "Escaped in %d minute(s).\n", E.steps);
    }
    return 0;
}
posted on 2012-07-23 17:52  找回失去的  阅读(161)  评论(0编辑  收藏  举报