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:
- 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).
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
bwwb bbwb bwwb bwww
Sample Output
4
AC Code
#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <limits.h>
#include <queue>
#define inf 0x3f3f3f3f
using namespace std;
int map[5][5],sum=999,t[5][5],dir[][2]={-1,0,1,0,0,1,0,-1};
void fz()
{
int i,j;
for(i=1;i<=4;i++)
for(j=1;j<=4;j++)
t[i][j]=map[i][j];
}
void change(int x,int y)
{
int tx,ty;
t[x][y]=!t[x][y];
for(int i=0;i<4;i++)
{
tx=x+dir[i][0];
ty=y+dir[i][1];
if(tx<1||tx>4||ty<1||ty>4) continue;
t[tx][ty]=!t[tx][ty];
}
return;
}
bool pd()
{
bool flag=1;
int d=t[1][1],i,j;
for(i=1;i<=4;i++)
for(j=1;j<=4;j++)
if(t[i][j]!=d)
{
flag=0;
break;
}
return flag;
}
int main(int argc, char** argv) {
int i,j;
for(i=1;i<=4;i++)
for(j=1;j<=4;j++)
{
char tmp;
cin>>tmp;
if(tmp=='w') map[i][j]=0;
else map[i][j]=1;
}
fz();
if(pd()) cout<<0<<endl;
else
{
for(i=1;i<(1<<16);i++)
{
int count=0,x,y;
fz();
for(j=0;j<16;j++)
if(i&(1<<j))
{
count++;
x=j/4+1;
y=j%4+1;
change(x,y);
}
if(pd()&&count<sum) sum=count;
}
if(sum==999) cout<<"Impossible"<<endl;
else cout<<sum<<endl;
}
return 0;
}