Flip Game
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
bwwb
bbwb
bwwb
bwww
Sample Output
4
题意: 在4*4的方格上,有两种颜色的棋子黑色和白色,每次在16个格子中任选一个改变其颜色,它周围上下左右的四个棋子也改变颜色,黑变白,白变黑,现要求将这16个格子变成都是白的或者黑的至少要翻多少次,如果不能的话就输出Impossible。
分析:总共有16个格子,说明最多也就翻16次,总共有2^16种可能,所以枚举一下,用dfs。
代码:
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<vector>
#include<math.h>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
int mp[6][6];
int step;//次数
int flag;//标记是否成功
int dx[5]={0,1,0,-1,0};//翻转的五个位置
int dy[5]={0,0,1,0,-1};
int judge (){//判断是否全都为一种颜色
for (int i=1;i<=4;i++){
for (int j=1;j<=4;j++){
if (mp[i][j]!=mp[1][1]){
return 0;
}
}
}
return 1;
}
void flip(int x,int y){//翻转的操作
for (int i=0;i<5;i++){
mp[x+dx[i]][y+dy[i]]^=1;
}
}
void dfs(int x,int y,int deep){
if (step==deep){//如果次数到了判断是否一样
flag=judge();
return;
}
if (flag||x>4)return;//如果已经枚举所有情况或者已经成功了就结束
flip(x,y);//翻转
if (y<4){
dfs(x,y+1,deep+1);
}
else {
dfs(x+1,1,deep+1);
}
flip(x,y);//不成功就翻转回来,然后枚举下一个情况
if (y<4){
dfs(x,y+1,deep);
}
else dfs(x+1,1,deep);
return;
}
int main ()
{
char c;
memset (mp,0,sizeof (mp));
flag=0;
for (int i=1;i<=4;i++){
for (int j=1;j<=4;j++){
cin>>c;
if (c=='b') mp[i][j]=1;
else mp[i][j]=0;
}
}
for (step=0;step<=16;step++){
dfs(1,1,0);
if (flag)break;//成功就跳出来
}
if (flag)printf ("%d\n",step);
else printf ("Impossible\n");
return 0;
}