hdu_1253_胜利大逃亡(bfs+剪枝)

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1253

题意:三维BFS,不解释

题解:DFS+剪枝会超时,裸BFS会超时,BFS+剪枝才能AC,有点伤,我以为数据会让DFS速度快一下,看来是我天真了难过

#include<cstdio>
#include<queue>
using namespace std;
#define FFC(i,a,b) for(int i=a;i<=b;i++)
int g[51][51][51],a,b,c,ti,ok,ts,dir[6][3]={0,0,1,0,0,-1,0,1,0,0,-1,0,1,0,0,-1,0,0};
bool v[51][51][51];
struct dt{int x,y,z,time;};
bool check(int x,int y,int z,int tt){
	if(v[x][y][z]||g[x][y][z]||x<1||x>a||y<1||y>b||z<1||z>c||tt>ti)return 0;
	else if(a+b+c-x-y-z+tt>ti)return 0;//剪枝
	return 1;
}
void fuck(){
	dt s,now;s.x=1,s.y=1,s.z=1,s.time=0;
	queue<dt>Q;Q.push(s);
	while(!Q.empty()){
		now=Q.front();Q.pop();
		if(now.x==a&&now.y==b&&now.z==c){ok=now.time;return;}
		for(int i=0;i<6&&ok==-1;i++){
		int xx=now.x+dir[i][0],yy=now.y+dir[i][1],zz=now.z+dir[i][2];
		if(!check(xx,yy,zz,now.time+1))continue;
		s.x=xx,s.y=yy,s.z=zz,s.time=now.time+1,v[xx][yy][zz]=1;
		Q.push(s);
		}
	}
}
int main(){
	scanf("%d",&ts);
	while(ts--){
		scanf("%d%d%d%d",&a,&b,&c,&ti);ok=-1;
		FFC(i,1,a)FFC(j,1,b)FFC(k,1,c){scanf("%d",&g[i][j][k]);v[i][j][k]=0;}
		fuck();
		printf("%d\n",ok);
	}
	return 0;
}


你可能感兴趣的:(bfs)