这道题,如何把三维的立体图信息存放在程序当中是关键,运用了三维数组,map[x][y][z];输入的时候三个for循环就可以搞定了。由于题目是以x为变量分为第0块,第一块,第二块,所以最外层以x为循环变量。解决了这 个,接下来就是和bfs常用做法一致了,父节点(0,0,0)先入队,有六个方向可以走,所以在判六个方向的子节点符不符合入队条件:不能越界(这里有一种方法是把最外层一圈全部设置成墙,那样就不用判断越界了,只用判断是墙还是路),必须是路,没有被访问过。符合条件,入队,重复以上操作,直到某个子节点到达终点,并且时间小于t,则返回到达这点的时间。否则如果一直没有找到这样一个点,bfs函数返回-1.
#include<stdio.h>
#include<iostream>
#include<queue>
#include<string.h>
#define maxn 50+5
using namespace std;
int map[maxn][maxn][maxn];
bool visit[maxn][maxn][maxn];
int A,B,C,t;
typedef struct Node{
int x;
int y;
int z;
int time;
}node;
typedef struct dir{
int tx;
int ty;
int tz;
}dir1;
dir1 dire[6]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
int abs(int a){
return a<0?-a:a;
}
bool check(node a){
if(a.x<0||a.x>=A||a.y<0||a.y>=B||a.z<0||a.z>=C||map[a.x][a.y][a.z])
return false;
return true;
}
queue <node> q;
int bfs(int a,int b,int c){
node head,next;
head.x=a;
head.y=b;
head.z=c;
head.time=0;
q.push(head);
visit[head.x][head.y][head.z]=true;
while(!q.empty())
{
head=q.front();
q.pop();
for(int i=0;i<6;i++)
{
next.x=head.x+dire[i].tx;
next.y=head.y+dire[i].ty;
next.z=head.z+dire[i].tz;
if(!visit[next.x][next.y][next.z]&&check(next))
{
next.time=head.time+1;
if(next.x==A-1&&next.y==B-1&&next.z==C-1&&next.time<=t)
return next.time;
visit[next.x][next.y][next.z]=true;
if(abs(next.x-A+1)+abs(next.y-B+1)+abs(next.z-C+1)+next.time>t)
continue;
q.push(next);
}
}
}
return -1;
}
int main()
{
int K;
scanf("%d",&K);
while(K--)
{
memset(map,0,sizeof(map));
memset(visit,false,sizeof(visit));
scanf("%d%d%d%d",&A,&B,&C,&t);
for(int x=0;x<A;x++)
for(int y=0;y<B;y++)
for(int z=0;z<C;z++)
scanf("%d",&map[x][y][z]);
while(!q.empty()) q.pop();
printf("%d\n",bfs(0,0,0));
}
return 0;
}
编写过程中还是出现了很多小错误,比如判断是否越界时,将想x<0,x >=A;等一系列越界的特征用&&连接了,还有判断子节点是否到达目标时,把判断条件,写到了判断是否能够访问到这个子节点之外。还有就是把z