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
#include
#include
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 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