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:
Choose any one of the 16 pieces.
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.
当第一行走的步确定以后如果第一行没被处理完,就只能通过第二行操作去修改,以此类推,次行都填补当前行的坑,所以当第一行要走的步确定以后整个棋局的要走的步就确定了
状态压缩,把第一行反转的表示为1,不操作的为0,全部的状态为0~1<<4-1;
#include<iostream>
using namespace std;
char mp[5][5],fb[5][5];
int a[5]={0,1,-1,0,0},b[5]={0,0,0,1,-1};
const int inf=1e6;
int temp(int x)
{
int ans=0;
while(x) ans+=(x&1),x>>=1;
return ans;
}
void to(int p,int h)
{
for(int i=1;i<=4;i++)
{
if((p&(1<<(i-1)))==0) continue;
fb[h][i]=(fb[h][i]=='w')?'b':'w';
for(int f=1;f<=4;f++)
{
int x=h+a[f],y=i+b[f];
if(x>=1&&x<=4&&y>=1&&y<=4) fb[x][y]=(fb[x][y]=='w')?'b':'w';
}
}
}
long long solve(int p,char c)
{
int ans=0;
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
fb[i][j]=mp[i][j];
for(int j=1;j<=4;j++)
{
ans+=temp(p);
to(p,j);
p=0;
for(int k=1;k<=4;k++) if(fb[j][k]!=c) p|=1<<(k-1);
}
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
if(fb[i][j]!=c) return inf;
return ans;
}
int main()
{
for(int i=1;i<=4;i++) cin>> (mp[i]+1);
long long ans=inf;
for(int i=0;i<=(1<<4)-1;i++)
{
ans=min(ans,solve(i,'w'));
ans=min(ans,solve(i,'b'));
}
if(ans==inf) cout<<"Impossible";
else cout<<ans;
}