POJ1753 Flip Game 位运算+搜索

来源:互联网 发布:手机预算软件 编辑:程序博客网 时间:2024/05/16 13:39

Flip Game
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 46458 Accepted: 19890

Description

Flip game is played on a rectangular 4x4 field with two-sided pieces placed on each of its 16 squares. One side of each piece is white and the other one is black and each piece is lying either it's black or white side up. Each round you flip 3 to 5 pieces, thus changing the color of their upper side from black to white and vice versa. The pieces to be flipped are chosen every round according to the following rules: 
  1. Choose any one of the 16 pieces. 
  2. Flip the chosen piece and also all adjacent pieces to the left, to the right, to the top, and to the bottom of the chosen piece (if there are any).

Consider the following position as an example: 

bwbw 
wwww 
bbwb 
bwwb 
Here "b" denotes pieces lying their black side up and "w" denotes pieces lying their white side up. If we choose to flip the 1st piece from the 3rd row (this choice is shown at the picture), then the field will become: 

bwbw 
bwww 
wwwb 
wwwb 
The goal of the game is to flip either all pieces white side up or all pieces black side up. You are to write a program that will search for the minimum number of rounds needed to achieve this goal. 

Input

The input consists of 4 lines with 4 characters "w" or "b" each that denote game field position.

Output

Write to the output file a single integer number - the minimum number of rounds needed to achieve the goal of the game from the given position. If the goal is initially achieved, then write 0. If it's impossible to achieve the goal, then write the word "Impossible" (without quotes).

Sample Input

bwwbbbwbbwwbbwww

Sample Output

4

Source

Northeastern Europe 2000

题意 :一个4*4的棋盘上有棋子,一面黑,一面白,其中翻转一颗棋子,它的上下左右都会翻转。问最少多少次能翻转成同一种颜色。

思路:将矩阵换成一个数字,这个数字二进制为16位,1代表b,0代表w。然后搜索。如例子转换成数的二进制为1001110110011000。另外,同一个位置翻转两次没有意义。

#include<stdio.h>int ans=200000;int m[16]={1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768};//用来转换成数void slove(int x,int f,int st){    if(f==65535||f==0)//当所有都为黑色或当所有都为白色,回溯    {        if(ans>st)            ans=st;        return ;    }    if(x==17)//翻转次数超过16回溯        return;    if(st>=ans)//翻转次数超过最小次数,回溯        return;    slove(x+1,f,st);//这个位置不翻转,进行搜索。    f^=(1<<((17-x)-1));//翻转本身。    if(x%4!=0)        f^=(1<<((17-x-1)-1));//翻转右边    if(x%4!=1)        f^=(1<<((17-x+1)-1));//翻转左边    if(x>4)        f^=(1<<((17-x+4)-1));//翻转上边    if(x<=12)        f^=(1<<((17-x-4)-1));//翻转下边    slove(x+1,f,st+1);//翻转后搜索}int main(){    int s=0;    for(int i=1;i<=4;i++)    {        for(int j=1;j<=4;j++)        {            char c;            scanf("%c",&c);            if(c=='b')                s+=m[16-4*i+4-j];//将矩阵变成一个数。        }        getchar();    }    slove(1,s,0);    if(ans==200000)        printf("Impossible\n");    else        printf("%d\n",ans);}