bfs-HDU 1253 胜利大逃亡

三维迷宫BFS求解
本文介绍了一个三维迷宫问题的BFS求解方法,通过对比DFS发现BFS在某些情况下能更有效地找到从起点到终点的最短路径。文章提供了一份完整的C++代码实现,并说明了如何通过队列来遍历所有可能的状态。

重点这题是三维的。要找好始末位置!

做了这么久才发现了一道在最优解的问题上bfs dfs有矛盾的题。

dfs交了N发过不去。bfs写了两发就过了。

#include <iostream>
#include <stdio.h>
#include <queue>
#include <cstring>
using namespace std;
struct node
{
    int x,y,z,step;
};
int mp[55][55][55];
int vis[55][55][55];
int yes;
int ans=999999;
int over;
int A,B,C;
queue <node> s;
void bfs()
{
    int step=0;
    node t;
    t.x=1;
    t.y=1;
    t.z=1;
    t.step=0;
    s.push(t);
    vis[1][1][1]=1;
    while(!s.empty())
    {
        t=s.front();
        s.pop();
        if(t.step>over)
        {
            printf("-1\n");
            return ;
        }
        if(t.z==A&&t.x==B&&t.y==C)
        {
            printf("%d\n",t.step);
            return ;
        }
        int next[10][5]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
        for(int i=0;i<6;i++)
        {
            node temp=t;
            temp.z+=next[i][0];
            temp.x+=next[i][1];
            temp.y+=next[i][2];
            if(temp.x<1||temp.y<1||temp.z<1||temp.x>B||temp.y>C||temp.z>A||vis[temp.z][temp.x][temp.y]!=0||mp[temp.z][temp.x][temp.y])
                continue;
            temp.step++;
            vis[temp.z][temp.x][temp.y]=1;
            s.push(temp);
        }


    }
    printf("-1\n");
    return ;
}
int main()
{
    int K;
    scanf("%d",&K);
    while(K--)
    {
        memset(vis,0,sizeof(vis));
        scanf("%d%d%d%d",&A,&B,&C,&over);
        for(int i=1;i<=A;i++)
        {
            for(int n=1;n<=B;n++)
            {
                for(int m=1;m<=C;m++)
                {
                    scanf("%d",&mp[i][n][m]);
                }
            }
        }
        bfs();
    }
    return 0;
}
/*
1
2 2 2 3
0 0
0 1
0 0
0 1

*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值