HDOJ-1253(BFS + 特判)

博客讲述了作者在解决HDOJ-1253问题时,初次使用BFS算法导致超时。通过查阅他人AC方案,发现需要特殊判断。在调整代码后,提交过程中注意到不同编译器对代码效率的影响,即便是微小改动如删除头文件,也会导致显著性能差距。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一开始上来就BFS,交了好几次都超时,无奈网搜了一下别人AC了的博客,原来要特判一下,真是迟钝呢,不过提交的过程中竟然发现不同的编译器效果有这么大的差距,下图中代码大小差距只是第二次交的时候删掉了一个头文件而已,真是给跪了

#include <cstdio>
#include <queue>
using namespace std;

const short MAX = 50;
const short MOVE[6][3] = {
    {1, 0, 0}, {-1, 0, 0},
    {0, 1, 0}, {0, -1, 0},
    {0, 0, 1}, {0, 0, -1}
};

struct Point{
    short x, y, z;
};

short A, B, C, T;        //3D edge length and time
short map[MAX][MAX][MAX];//map

inline bool isUnreachable(short x, short y, short z)
{
    return x < 0 || x >= A ||
           y < 0 || y >= B ||
           z < 0 || z >= C ||
           map[x][y][z]    ;
}
short bfs()
{
    //if dest is blocked or distance is already more than time given
    if(map[A-1][B-1][C-1] || A + B + C - 3 > T) return -1;
    //if dest is start
    if(A == 1 && B == 1 && C == 1) return 0;
//step 1: initialize
    Point now = {0, 0, 0}, nex;
    queue<Point> q;
    q.push(now);
    map[0][0][0] = 1;//set visited blocked
//step 2: T level BFS
    for(short t = 0; t < T && !q.empty(); ++t){
        for(short n = q.size(); n > 0; --n){
            now = q.front();
            q.pop();
            for(short i = 0; i < 6; ++i){
                nex.x = now.x + MOVE[i][0];
                nex.y = now.y + MOVE[i][1];
                nex.z = now.z + MOVE[i][2];
                if(isUnreachable(nex.x, nex.y, nex.z)) continue;
                if(nex.x + 1 == A && nex.y + 1 == B && nex.z + 1 == C) return t + 1;
                q.push(nex);
                map[nex.x][nex.y][nex.z] = 1;//set visited blocked
            }
        }
    }

    return -1;
}

int main()
{
    short test;

    for(scanf("%d", &test); test > 0; --test){
        //input map
        scanf("%d %d %d %d", &A, &B, &C, &T);
        for(short i = 0; i < A; ++i){
            for(short j = 0; j < B; ++j){
                for(short k = 0; k < C; ++k) scanf("%d", &map[i][j][k]);
            }
        }
        //check if can get out
        printf("%d\n", bfs());
    }

    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值