ACM题解报告——HD1253

  今天AC了杭电OJ的1253题《胜利大逃亡》,题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1253

  该题目是一个比较经典立方体迷宫问题,要求在给定的时间内从始点(0,0,0)逃到出口(a-1,b-1,c-1),这里我采用的是BFS(宽度优先搜索)。

  代码如下:

#include<iostream>
using namespace std;
int map[55][55][55],a,b,c,times,visit[55][55][55];
int fx[6]={1,-1,0,0,0,0},fy[6]={0,0,1,-1,0,0},fz[6]={0,0,0,0,1,-1};
typedef struct 
{
  int x;
  int y;
  int z;
  int t;
}Node;
Node node[125005];
int check(int p,int q,int x)
{
  int flag=1;
if(p<0||p>=a||q<0||q>=b||x<0||x>=c)
  flag=0;
 else if(visit[p][q][x]==1)
  flag=0;
else if( map[p][q][x]==1)
  flag=0;
 return flag;
}
void bfs(int m,int n,int h)
{
  int i,head,tail,p,q,x;
  head=0;
  tail=1;
  node[1].x=m;
  node[1].y=n;
  node[1].z=h;
  node[1].t=0;
if(m==a-1&&n==b-1&&h==c-1)  
{
  cout<<"0"<<endl;
  return ;
 }
  while( head!=tail)
{
  head++;
  for(i=0;i<6;i++)
{
  p=node[head].x+fx[i];
  q=node[head].y+fy[i];
  x=node[head].z+fz[i];
  if(check(p,q,x)==1)
{
  tail++;
  node[tail].x=p;
  node[tail].y=q;
  node[ tail].z=x;
  node[tail].t=node[head].t+1;
  visit[node[ tail].x][node[tail].y][node[tail].z]=1;
  if(node[tail].x==a-1&&node[tail].y==b-1&&node[tail].z==c-1 )
{
  if(node[tail].t>times)  
{
  cout<<"-1"<<endl;
 }
  else
    cout<<node[ tail].t<<endl;
  return ;
 }
 }
 }
 }
cout<<"-1"<<endl;
}
int main( )
{
  int i,j,k,t;
  scanf( "%d",&t);
 while(t--)
{
  scanf("%d%d%d%d",&a,&b,&c,&times);
  memset(visit,0,sizeof(visit));
  for(i=0;i<a;i++)
    for(j=0;j<b;j++)
      for( k=0;k<c;k++)
        scanf("%d",&map[i][j][k]);
  bfs(0,0,0);

}
  return 0;
}

hdoj上要C++才能AC,大概900MS左右,G++的话会超时的。

  

posted @ 2013-05-27 15:51  paradise in hell  Views(193)  Comments(0Edit  收藏  举报