题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1253
BFS 水题。
A是z轴
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
int k,a,b,c,t,vis[60][60][60],map[60][60][60];
int dx[]={1,-1,0,0,0,0};
int dy[]={0,0,1,-1,0,0};
int dz[]={0,0,0,0,1,-1};
struct node
{
int x,y,z,time;
};
void bfs(int z,int x,int y)
{
node vw,vn;
queue<node>q;
int flag=0,ans;
vn.x=vn.y=vn.z=vn.time=0;
vis[0][0][0]=1;
q.push(vn);
while(!q.empty())
{
vn=q.front();
q.pop();
if(vn.time>t)
{
break;
}
if(vn.z==z&&vn.x==x&&vn.y==y&&vn.time<=t)
{
ans=vn.time;
flag=1;
break;
}
else
{
int i;
for(i=0;i<6;i++)
{
vw.x=vn.x+dx[i];
vw.y=vn.y+dy[i];
vw.z=vn.z+dz[i];
if(vw.z>=0&&vw.z<a&&vw.x>=0&&vw.x<b&&vw.y>=0&&vw.y<c&&!vis[vw.x][vw.y][vw.z]&&map[vw.x][vw.y][vw.z]==0)
{
vis[vw.x][vw.y][vw.z]=1;
vw.time=vn.time+1;
q.push(vw);
}
}
}
}
if(!flag)
printf("-1\n");
else
printf("%d\n",ans);
}
int main()
{
scanf("%d",&k);
while(k--)
{
scanf("%d%d%d%d",&a,&b,&c,&t);
int x,y,z;
memset(vis,0,sizeof(vis));
for(z=0;z<a;z++)
for(x=0;x<b;x++)
for(y=0;y<c;y++)
scanf("%d",&map[x][y][z]);
bfs(z-1,x-1,y-1);
}
return 0;
}