POJ 1753 Flip Game (bfs)

 

 

 

#include<cstdio>

#include<cstring>

#include<iostream>

#include<algorithm>

#include<queue>

using namespace std;

int ch[20];

int op[4][2]={1,0, -1,0, 0,1, 0,-1};

int mat[200000];

int vis[200000];

void init_ch()

{

    int i,j,k;

    int temp;

    int cnt=0;

    for(i=0;i<4;i++)

    {

        for(j=0;j<4;j++)

        {

            temp=0;

            temp^=(1<<((3-i)*4+(3-j)));

            for(k=0;k<4;k++)

            {

                int x=i+op[k][0];

                int y=j+op[k][1];



                if(x<0||x>3||y<0||y>3) continue;

                temp^=(1<<((3-x)*4+(3-y)));

            }

            ch[cnt++]=temp;

        }

    }

}

void init_ans()

{

    mat[0]=0;

    int i,j,k;

    queue<int> q;

    q.push(0);

    while(!q.empty())

    {

        int now=q.front();

        int next;

        vis[now] = 1;

        q.pop();



        for(i=0;i<16;i++)

        {

            next=now^ch[i];

            if(vis[next]==0)

            {vis[next]=1;

                mat[next]=mat[now]+1;

                q.push(next);

            }

        }

    }

}

int main()

{

   int i,j,k;

   memset(vis,0,sizeof(vis));

   memset(mat,-1,sizeof(mat));

   init_ch();

   init_ans();

   char str[10][10];

   while(scanf("%s",str[0])!=EOF)

   {

       for(i=1;i<4;i++)

       {

           scanf("%s",str[i]);

       }



       /*

       for(i=0;i<4;i++)

       {

           printf("%s\n",str[i]);

       }

       printf("\n");

       */



       int now=0,now1=0;

       for(i=0;i<4;i++)

       {

           for(j=0;j<4;j++)

           {

               now1<<=1;

               now<<=1;

               if(str[i][j]=='b') now+=1;

               if(str[i][j]=='w') now1+=1;

               //printf("%d %d\n",i,now);

           }

       }

       //now1=now^(1<<16-1);



       int ans;



       if(vis[now]==0&&vis[now1]==0)

       {

           printf("Impossible\n");

       }

       else if(vis[now]==0)

       {

           printf("%d\n",mat[now1]);

       }

       else if(vis[now1]==0)

       {

           printf("%d\n",mat[now]);

       }

       else printf("%d\n",min(mat[now],mat[now1]));





   }

    return 0;

}

 

你可能感兴趣的:(game)