HDU 1253 胜利大逃亡(简单三维BFS)

HDU 1253 胜利大逃亡(简单三维BFS)

http://acm.hdu.edu.cn/showproblem.php?pid=1253

题意:

        有一个A*B*C的三维网格,问你从起点(0,0,0)走到终点(A-1,B-1,C-1)最少需要花多少时间.且网格中有障碍格.

分析:

        三维网格的难点在于想象出一个符合二维BFS要求的图形.

        如果只有2维,那么就是B*C的二维网格了,很好处理,现在有A这第三维,我们只需要按上图A看成是二维网格的厚度即可.且本题的输入也是按厚度输入的.也即在原有维度r和c的基础上,多了一个h厚度新维度.

       在原上下左右4方向的基础上,增加了前后两个行走方向.

       注意此题要用C++提交,不能用G++提交.否则超时.

AC代码:

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=50+5;
int dh[]={0,0,0,0,1,-1};//上下左右前后
int dr[]={-1,1,0,0,0,0};
int dc[]={0,0,-1,1,0,0};
int A,B,C,T;
int map[maxn][maxn][maxn],dist[maxn][maxn][maxn];//map[h][r][c],dist[h][r][c]
struct Node
{
    int h,r,c;
    Node(int h,int r,int c):h(h),r(r),c(c){}
};
int BFS()//返回到终点的时间(不可达,返回-1),如果该时间>T也返回-1
{
    queue<Node> Q;
    memset(dist,-1,sizeof(dist));
    Q.push(Node(0,0,0));
    dist[0][0][0]=0;
    while(!Q.empty())
    {
        Node node=Q.front(); Q.pop();
        int h=node.h, r=node.r, c=node.c;
        for(int d=0;d<6;d++)
        {
            int nh=h+dh[d], nr=r+dr[d], nc=c+dc[d];
            if(nh<0||nh>=A||nr<0||nr>=B||nc<0||nc>=C||map[nh][nr][nc]==1||dist[nh][nr][nc]!=-1) continue;
            dist[nh][nr][nc]=dist[h][r][c]+1;
            Q.push(Node(nh,nr,nc));
            if(nh==A-1&&nr==B-1&&nc==C-1)
            {
                if(dist[nh][nr][nc]>T) return -1;
                return dist[nh][nr][nc];
            }
        }
    }
    return -1;
}
int main()
{
    int kase;scanf("%d",&kase);
    while(kase--)
    {
        scanf("%d%d%d%d",&A,&B,&C,&T);
        for(int i=0;i<A;i++)
        for(int j=0;j<B;j++)
        for(int k=0;k<C;k++)
            scanf("%d",&map[i][j][k]);
        printf("%d\n",BFS());
    }
    return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值