poj 1753 Flip game 枚举

BFS搜索 + 位运算提速。。枚举每一个状态, 进行up, left, down, right操作。。
当状态state = 0xffff 或0时,说明全部为黑或白。。。

对于一个状态没有访问过就入队,并且标志为已访问。。

View Code
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <queue>
using namespace std;

char mp[100];
int visit[76000];

struct node
{
  int state;// state value
  int num; // flip num 
}p;


void bfs( )
{ 
  int flag = 0;
  queue<node>q;
  q.push(p);
  visit[p.state] = 1;
  while( !q.empty() )
  {
     p = q.front();
     q.pop( );
     node qq;
     qq.state = p.state;
     for( int i = 0; i < 16; i++)
     {
        p.state = qq.state;
        p.state = p.state ^ ( 1 << i );
        // up
        if( i >= 4 )
           p.state = p.state ^ ( 1 << ( i -4 ) );
        // down
        if( i <= 11 )
           p.state = p.state ^ ( 1 << ( i + 4 ) ); 
        // left
        if( i % 4 != 0 )
          p.state = p.state ^ ( 1 << ( i - 1 ));
       //right
        if ( (i + 1) % 4 != 0 )
      p.state = p.state ^ ( 1 << ( i + 1 ) );
         
        if( p.state == 0xffff || p.state == 0 )
        {   
              flag = 1;
              cout<<p.num +  1 << endl;
              return;
 
        }
        if( visit[p.state] == 0 )
        {
            node temp;
            temp.num = p.num + 1;
            temp.state = p.state;
            visit[p.state] = 1;
            q.push(temp);

        }

   }
 }
 if( !flag )
   puts("Impossible");
}



int main( )
{
    memset(visit, 0, sizeof(visit));
    p.num = 0, p.state = 0;
    for( int i = 0; i < 16;i++)
    {
       cin>>mp[i];     
    } 
    for( int i = 0; i < 16; i++)
    {
      if( mp[i] == 'b' )
    p.state += (1<<i);

    }
    if( p.state == 0xffff || p.state == 0 )
   {
        puts("0");
   }
    else
   {
     bfs( );
   }
  return 0;
}

posted on 2012-07-08 17:02  more think, more gains  阅读(148)  评论(0编辑  收藏  举报

导航