HDU 1175 连连看

该题与HDU 1728 逃离迷宫是一样的解题思路http://acm.hdu.edu.cn/showproblem.php?pid=1728;这里我采取的方法还是一直走到底,如果没有路了就代表一定要转完了。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct T
{
   int x,y,turn;
}q[1000024];
int map[1024][1024],n,m,k;
int d[4][2]={ 0,1,1,0,0,-1,-1,0  };
int hash[1024][1024];
int inline push( const int x,const int y,const int turn,int end )
{
    T t;
    t.x=x;t.y=y;
    t.turn=turn;
    q[ end++ ] = t;
    return end;    
}
bool inline judge( int x,int y )
{
   if( x>n||x<=0||y>m||y<=0 ) 
     return false;
   else if( map[x][y]==0 )
         return true;
        else return false;    
}
bool inline BFS( int X1,int Y1,int X2,int Y2 )
{
    memset( hash,0,sizeof( hash ) );
    int first=0,end=0;
    end=push( X1, Y1, -1, end );
    hash[X1][Y1]=1;
    while( first< end )
    {
        if( q[first].turn>=2 ) return false;
        for( int i=0;i<4; i++ )
        {
           int dx=q[first].x + d[i][0];
           int dy=q[first].y + d[i][1];
           int turn=q[first].turn + 1;
           while( judge( dx,dy )||( dx==X2 && dy == Y2 ) ) 
           {
              //    printf( "%d %d\n",dx,dy );
                if( dx==X2 && dy == Y2 && map[dx][dy]==map[X1][Y1] ) 
                    return true;
                if( !hash[dx][dy] )
                {
                  hash[dx][dy]=1;
                  end = push( dx,dy,turn,end );    
                }
                dx += d[i][0];
                dy += d[i][1];       
           }    
        }
        first++;       
    }
    return false;     
}
int main()
{ 
   int x,X1,Y1,X2,Y2;
   while( scanf( "%d%d",&n,&m ),n||m )
   {
      for( int i=1;i<=n;i++ )
        for( int j=1;j<=m;j++ )
            scanf( "%d",&map[i][j] );
       scanf( "%d",&x );
      for( int i=0;i<x; i++ )
      {
          scanf( "%d%d%d%d",&X1,&Y1,&X2,&Y2 );
          if( X1==X2&&Y1==Y2 ) 
            printf( "NO\n" ); 
          else
          {
              if( map[X1][Y1]!=0&&map[X1][Y1]==map[X2][Y2]&&BFS( X1,Y1,X2,Y2 ) )
                printf( "YES\n" ) ;
              else printf( "NO\n" );  
         }  
      }   
   }
   return 0;    
}

 

posted @ 2011-11-24 11:46  wutaoKeen  阅读(1097)  评论(0)    收藏  举报