hdu 1253 胜利大逃亡(三维BFS)
比二维的多了2个方向而已,530MS
#include <stdio.h>
#include <string.h>
#include <cmath>
using namespace std;
#define MAXSIZE 51
struct coor
{
int x,y,z;
int time;
}que[MAXSIZE*MAXSIZE*MAXSIZE];
const 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,T;
bool g[MAXSIZE][MAXSIZE][MAXSIZE],visited[MAXSIZE][MAXSIZE][MAXSIZE];
inline bool check(int x,int y,int z)
{
if(x<0 || y<0 || z<0 || x>=A || y>=B || z>=C) return false;
if(g[x][y][z] || visited[x][y][z]) return false;
return true;
}
inline bool dis(int x,int y,int z,const coor &pos)
{
int t = abs(x-A+1.0) + abs(y-B+1.0) + abs(z-C+1.0);
if(t + pos.time > T) return true;
return false;
}
bool bfs()
{
int i,j,k,l,front=-1,rear=-1;
coor out,in;
in.x=0;
in.y=0;
in.z=0;
in.time=0;
que[++rear]=in;
visited[0][0][0]=true;
while(front<rear)
{
out=que[++front];
if(out.x==A-1 && out.y==B-1 && out.z==C-1)
{
if(out.time>T) return false;
printf("%d\n",out.time);
return true;
}
if(out.time>T) return false;
for(l=0;l<6;l++)
{
i=out.x+dir[l][0];
j=out.y+dir[l][1];
k=out.z+dir[l][2];
if(!check(i,j,k)) continue;
visited[i][j][k]=true;
if(dis(i,j,k,out)) continue;
in.x=i;
in.y=j;
in.z=k;
in.time=out.time+1;
que[++rear]=in;
}
}
return false;
}
int main()
{
int i,j,k,t,cas;
scanf("%d",&cas);
while(cas--)
{
// memset(g,sizeof(false),sizeof(g));
memset(visited,false,sizeof(visited));
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",&t);
g[i][j][k] = t ? 1:0;
}
if(!bfs()) printf("-1\n");
}
return 0;
}
浙公网安备 33010602011771号