开始在杭电上做这题时先是超内存,然后是超时,剪枝了一下结果wrong了,最后参考了一下才AC;
代码:
#include<stdio.h>
#include<queue>
using namespace std;
int a[50][50][50],n,m,u,D;
int dx[7]={1,-1,0,0,0,0},dy[7]={0,0,1,-1,0,0},dz[7]={0,0,0,0,1,-1};
struct zhang
{
int x,y,z,time;
};
int bfs(int x,int y,int z)
{
queue<zhang>q;
zhang current,next;
current.x=x;
current.y=y;
current.z=z;
current.time=0;
q.push(current);
while(!q.empty())
{
current=q.front();
q.pop();
for(int i=0;i<6;i++)
{
next.x=current.x+dx[i];
next.y=current.y+dy[i];
next.z=current.z+dz[i];
if(current.time+1<=D&&next.x>=0&&next.y>=0&&next.z>=0&&next.x<n&&next.y<m&&next.z<u&&!a[next.x][next.y][next.z])
{
if(next.x==n-1&&next.y==m-1&&next.z==u-1)
{
return current.time+1;
}
next.time=current.time+1;
a[next.x][next.y][next.z]=1;
q.push(next);
}
}
}
return -1;
}
int main()
{
int T,i,j,k;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d%d",&n,&m,&u,&D);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
for(k=0;k<u;k++)
scanf("%d",&a[i][j][k]);
printf("%d\n",bfs(0,0,0));
}
return 0;
}