【三维bfs】HDU1253——胜利大逃亡

本文介绍三维BFS算法实现及优化技巧,详细解释了搜索方向、边界条件判断及时间限制等关键步骤,并提供了完整的C++代码示例。

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

来源:点击打开链接

三维BFS,比起二维BFS来说多了一维,但是也没什么难度。

第一次卡时间过,在大神的指导下明白了,还可以进行优化。

1、搜索方向变成了6个。

2、需要考虑到出口处为墙的情况。

3、如果有这个会大大提高效率:if(a+b+c-3>tarstep) {printf("-1\n");continue;}(起点与终点间最短路径大于时间限度)

CODE:

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

int dir[6][3]= {{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
int a,b,c,tarstep;
int mat[60][60][60];
int visited[60][60][60];


class node
{
public:
    int x;
    int y;
    int z;
    int step;
};

node s1,e1;

int judge(int x,int y,int z)
{
    if(x>=0 && x<a && y>=0 && y<b && z>=0 && z<c && mat[x][y][z]==0 && visited[x][y][z]==0)
        return 1;
    else
        return 0;
}

int bfs(node st,node ed)
{

    if(mat[ed.x][ed.y][ed.z]==1)//特判1
        return -1;
    if(a+b+c-3>tarstep) //特判2
    {
        return -1;
    }
    memset(visited,0,sizeof(visited));
    queue<node> q;
    node first,next;
    first.x=st.x;
    first.y=st.y;
    first.z=st.z;
    first.step=0;

    visited[first.x][first.y][first.z]=1;
    q.push(first);
    while(!q.empty())
    {
        first=q.front();
        q.pop();
        for(int i=0; i<6; i++)
        {
            next.x=first.x+dir[i][0];
            next.y=first.y+dir[i][1];
            next.z=first.z+dir[i][2];
            next.step=first.step+1;

            if(next.x==ed.x && next.y==ed.y && next.z==ed.z && next.step<=tarstep)
                    return next.step;

            if(judge(next.x,next.y,next.z))
            {
                    visited[next.x][next.y][next.z]=1;
                    q.push(next);

            }
        }
    }
    return -1;
}

int main()
{
    int testcase;
    scanf("%d",&testcase);
    while(testcase--)
    {

        scanf("%d%d%d%d",&a,&b,&c,&tarstep);

        for(int i=0;i<a;i++)
        {
            for(int j=0;j<b;j++)
            {
                for(int k=0;k<c;k++)
                {
                    scanf("%d",&mat[i][j][k]);
                }
            }
        }
        s1.x=0;
        s1.y=0;
        s1.z=0;
        s1.step=0;
        e1.x=a-1;
        e1.y=b-1;
        e1.z=c-1;
        e1.step=0;
        int res=bfs(s1,e1);
        printf("%d\n",res);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值