题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1253
方法:bfs
思路:很常规的三维广搜,但是问题是这个题的数据量很大,直接广搜超时了好几发。需要在一些细节上做一些修改,比如,在广搜过程中一旦发现目前时间已经超过了规定时间,立刻返回。如果这一过程等到bfs结束后在main函数里判断,则会超时。这样做会一旦有一组数据出现了超过规定时间,那么就会立刻终止搜索,在多组数据的测试情况下是一种减缓耗时的办法,但是效果上并不是非常好,我也是刚刚擦边过的,1996ms。也可以在下一步继续走的判定过程中加入条件的限制,比如假设当前点与重点直接走都不能满足时间要求的话,则立刻放弃该点,这样做的话情况会稍好一些,我测试的是1216ms。
难点:细节处理缩短bfs搜索时间。
#include<cstdio>
#include<queue>
#include<cstring>
#include<cmath>
using namespace std;
const int MAX = 55;
int maze[MAX][MAX][MAX];
bool mark[MAX][MAX][MAX];
int dir[6][3] = {1,0,0,0,0,1,0,1,0,-1,0,0,0,-1,0,0,0,-1};
int a,b,c,T;
int ans = -1;
struct node
{
int x,y,z,step;
};
bool check(node p)
{
if(p.x >= a || p.x < 0 || p.y >= b || p.y < 0 || p.z >= c || p.z < 0)
return 1;
if(maze[p.x][p.y][p.z] == 1)
return 1;
if(mark[p.x][p.y][p.z] == 1)
return 1;
return 0;
}
void bfs()
{
memset(mark,0,sizeof(mark));
node p,t,next;
queue<node> Q;
p.x = 0;
p.y = 0;
p.z = 0;
p.step = 0;
mark[0][0][0] = 1;
Q.push(p);
while(!Q.empty())
{
t = Q.front();
Q.pop();
if(t.step > T)
continue;
if(t.x == a-1 && t.y == b-1 && t.z == c-1 && t.step <= T)
{
ans = t.step;
return;
}
for(int i = 0;i < 6;i++)
{
next.x = t.x+dir[i][0];
next.y = t.y+dir[i][1];
next.z = t.z+dir[i][2];
if(!check(next))
{
next.step = t.step+1;
mark[next.x][next.y][next.z] = 1;
if(abs(next.x-a+1) +abs(next.y-b+1)+abs(next.z-c+1) > T)
continue;
Q.push(next);
}
}
}
}
int main()
{
int n;
while(~scanf("%d",&n))
{
while(n--)
{
ans = -1;
scanf("%d%d%d%d",&a,&b,&c,&T);
for(int i = 0;i < a;i++)
{
for(int j = 0;j < b;j++)
{
for(int k = 0;k < c;k++)
{
scanf("%d",&maze[i][j][k]);
}
}
}
bfs();
if(ans == -1)
printf("-1\n");
else
printf("%d\n",ans);
}
}
}