hdu1253 胜利大逃亡(三维bfs)

本文讨论了BFS算法在三维场景搜索中的实现,包括数据结构设计、搜索过程和优化策略,通过实例展示了算法在解决实际问题时的效率和效果。

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

三维bfs,感觉搜索还很弱啊。。。

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <stdlib.h>

using namespace std;

const int N = 52;
const int INF = 1000000;

int Map[52][52][52], visit[52][52][52];
int a, b, c, t;

struct Poi
{
    int x, y, z;
    int t;
};

int dir[6][3] = {{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}, {0, 1, 0}, {0, -1, 0}};

int go(int x0, int y0, int z0)
{
    if(x0 >= 0 && x0 < a && y0 >= 0 && y0 < b && z0 >= 0 && z0 < c && Map[x0][y0][z0] == 0) return 1;
    else return 0;
}

int BFS(int m)
{
    Poi st, ed;
    queue <Poi> q;
    st.x = 0;
    st.y = 0;
    st.z = 0;
    st.t = 0;
    q.push(st);
    memset(visit, 0, sizeof(visit));
    visit[0][0][0] = 1;
    while(!q.empty())
    {
        st = q.front();
        q.pop();
        if(st.t > m) return -1;
        if(st.x == a - 1 && st.y == b - 1 && st.z == c - 1 && st.t <= m) return st.t;
        for(int i = 0; i < 6; i ++)
        {
            ed.x = st.x + dir[i][0];
            ed.y = st.y + dir[i][1];
            ed.z = st.z + dir[i][2];
            if(go(ed.x, ed.y, ed.z) && !visit[ed.x][ed.y][ed.z])
            {
                visit[ed.x][ed.y][ed.z] = 1;
                ed.t = st.t + 1;
                if(abs(a - (ed.x + 1)) + abs(b - (ed.y + 1)) + abs(c - (ed.z + 1)) + ed.t > m) continue; //剪枝预判
                q.push(ed);
            }
        }
    }
    return -1;
}
int main()
{
 //   freopen("in.txt", "r", stdin);
    int n, i, j, k, t;
    scanf("%d", &n);
    while(n --)
    {
        scanf("%d%d%d%d", &a, &b, &c, &t);
        for(i = 0; i < a; i ++)
            for(j = 0; j < b; j ++)
                for(k = 0; k < c; k ++)
                    scanf("%d", &Map[i][j][k]);
        printf("%d\n", BFS(t));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值