唔,最近感觉搜索好弱,明天开始做做搜索专题。

 

CODE:

 

#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <string.h>
using namespace std;

const int SIZE = 52;

int maze[SIZE][SIZE][SIZE];
int flag[SIZE][SIZE][SIZE];
int l, r, c, T;
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 bx, by, bz; 
int ex, ey, ez;

int check(int x, int y, int z)
{
    if(x >= 0 && y >= 0 && z >= 0 && x < l && y < r && z < c && maze[x][y][z] != 1return 1;
        return 0;
}


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


int bfs(int bx, int by, int bz, int T)
{
    queue<node> Q;
    node p, q;
    p.x = bx; p.y = by; p.z = bz;
    p.step = 0;
    flag[bx][by][bz] = 1;
    Q.push(p);
    while(!Q.empty())
    {
        p = Q.front();
        Q.pop();
        if(p.x == ex && p.y == ey && p.z == ez && p.step <= T)
        {
            return p.step;
        }
        for(int i = 0; i < 6; i++)
        {
            q = p;
            q.x += dx[i];
            q.y += dy[i];
            q.z += dz[i];
            if(!flag[q.x][q.y][q.z] && check(q.x, q.y, q.z))
            {
                q.step++;
                flag[q.x][q.y][q.z] = 1;
                if(abs(q.x-l+1)+abs(q.y-r+1)+abs(q.z-c+1)+q.step > T)
                continue;
                Q.push(q);
            }
        }
    }
    return -1;
}


void init()
{
    memset(flag, 0sizeof(flag));
    memset(maze, 1sizeof(maze));
}

int main()
{
    int i, j, k;
    int ca;
    scanf("%d", &ca);
    while(ca--)
    {
        init();
        scanf("%d%d%d%d", &l, &r, &c, &T);
        for(i = 0; i < l; i++)
        {
            for(j = 0; j < r; j++)
            {
                for(k = 0; k < c; k++)
                {
                    scanf("%d", &maze[i][j][k]);
                }
            }
        }
        bx = by = bz = 0;
        ex = l-1; ey = r-1; ez = c-1;
        int ans = bfs(bx, by, bz, T);
        printf("%d\n", ans);
    }
    return 0;
}

 

posted on 2012-09-23 21:16  有间博客  阅读(206)  评论(0编辑  收藏  举报