HDU1253 胜利大逃亡(搜索)

题目链接

这题就是BFS。也挺水的。。

看见这个时间差了吗。。很可惜。这并不是减枝。。只是同样的代码,用不同的编译器发罢了(汗。)。

#include <stdio.h>

#define MAXN 52

typedef struct Pos{
    int x, y, z;
    int cur;
}Pos;

int a, b, c;
int G[MAXN][MAXN][MAXN], vis[MAXN][MAXN][MAXN];
Pos queue[MAXN*MAXN*MAXN];

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

int bfs(){
    int front, rear, d;
    Pos pos = {0, 0, 0, 0}, npos;

    front = rear = 0;

    queue[rear++] = pos;
    vis[pos.x][pos.y][pos.z] = 1;

    while(front < rear){
        pos = queue[front++];
        if(pos.x == a-1 && pos.y == b-1 && pos.z == c-1) return pos.cur;
        for(d=0; d<6; d++){
            npos.x = pos.x+dx[d];
            npos.y = pos.y+dy[d];
            npos.z = pos.z+dz[d];
            npos.cur = pos.cur+1;
            if(npos.x >= 0 && npos.x < a && npos.y >= 0 && npos.y < b && npos.z >=0 && npos.z < c && !G[npos.x][npos.y][npos.z] && !vis[npos.x][npos.y][npos.z]){
                vis[npos.x][npos.y][npos.z] = 1;
                queue[rear++] = npos;
            }
        }
    }
    return -1;
}

int main(){
    int i, j, k, t, time_s, time_cost;

    scanf("%d", &t);
    while(t--){
        scanf("%d %d %d %d", &a, &b, &c, &time_s);

        for(i=0; i<a; i++)
            for(j=0; j<b; j++)
                for(k=0; k<c; k++){
                    scanf("%d", &G[i][j][k]);
                    vis[i][j][k] = 0;
                }

        time_cost = bfs();

        if(time_cost != -1 && time_cost <= time_s) printf("%d\n", time_cost);
        else printf("-1\n");
    }

    return 0;
}
原文地址:https://www.cnblogs.com/tanhehe/p/2932396.html