HDU 1548 A strange lift

该题是一道典型的BFS题,如果你用DFS你就会要把所有的肯能枚举,而BFS就不需要这样。

#include<stdio.h>
#include<stdlib.h>
struct T
{
int x, n;
}q[424];
int BFS( int n,int k[],int start,int end )
{
int first=0,tail=0,hash[224]={0};
T t;
hash[start]=1;
t.x=start;t.n=0;
q[first++]=t;
while( first>tail )
{
int count=q[tail].x-k[q[tail].x];
if( (count>0)&&(hash[count]==0))
{
if( count==end ) return q[tail].n+1;
hash[count]=1;
t.x=count;
t.n=q[tail].n+1;
q[first++]=t;
}
count=q[tail].x+k[q[tail].x];
if( (count<=n)&&hash[count]==0 )
{
if( count==end ) return q[tail].n+1;
hash[count]=1;
t.x=count;
t.n=q[tail].n+1;
q[first++]=t;
}
tail++;
}
return -1;
}
int main()
{
int n,start,end;
int k[224];
while( scanf( "%d",&n ),n )
{
scanf( "%d%d",&start, &end );
for( int i=1;i<=n;i++ )
scanf( "%d",&k[i] );
if( start==end ) printf( "0\n" );
else
printf( "%d\n",BFS( n,k,start,end ) );
}
return 0;
}

 

你可能感兴趣的:(HDU)