您的位置:首页 > 其它

HDOJ搜索专题之胜利大逃亡

2012-05-16 17:21 330 查看
BFS,走三维迷宫。

View Code

#include <stdio.h>
#include <string.h>
#include <queue>
#define N 50
using namespace std;
typedef struct node
{
int x,y,z;
}node;
queue<node> Q;
node cur,next;
int dx[6]={1,-1,0,0,0,0};
int dy[6]={0,0,1,-1,0,0};
int dz[6]={0,0,0,0,1,-1};
int g

,t

;
int a,b,c,tmax,ans;
void bfs()
{
bool success=false;
memset(t,0xff,sizeof(t));
cur.x=cur.y=cur.z=0;
t[0][0][0]=0;
while(!Q.empty()) Q.pop();
Q.push(cur);
while(!Q.empty() && !success)
{
cur=Q.front(),Q.pop();
ans=t[cur.x][cur.y][cur.z];
if(cur.x==a-1 && cur.y==b-1 && cur.z==c-1 && ans<=tmax) success=true;
for(int d=0;!success && d<6;d++)
{
next=cur;
next.x+=dx[d];
next.y+=dy[d];
next.z+=dz[d];
if(next.x<0 || next.x>=a) continue;
if(next.y<0 || next.y>=b) continue;
if(next.z<0 || next.z>=c) continue;
if(g[next.x][next.y][next.z]) continue;
if(t[next.x][next.y][next.z]!=-1) continue;
ans=t[next.x][next.y][next.z]=t[cur.x][cur.y][cur.z]+1;
if(next.x==a-1 && next.y==b-1 && next.z==c-1 && ans<=tmax) success=true;
else if(t[next.x][next.y][next.z]<tmax) Q.push(next);
}
}
if(success) printf("%d\n",ans);
else  puts("-1");
}
int main()
{
int T,i,j,k;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d%d",&a,&b,&c,&tmax);
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
for(k=0;k<c;k++)  scanf("%d",&g[i][j][k]);
}
}
bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: