链接:https://ac.nowcoder.com/acm/problem/106350
来源:牛客网
题目描述
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.
输入描述:
The input consists of 4 lines with 4 characters “w” or “b” each that denote game field position.
输出描述:
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).
示例1
输入
复制
bwwb
bbwb
bwwb
bwww
输出
复制
4
题目大意:给出一个4*4的棋盘,其中布满棋子,棋子可以是黑,也可以是白。现在你可以翻动棋子,规定每次翻动一个棋子其上下左右的棋子都会被翻动。问最少需要多少次能将棋子变为全黑或全白。
题解:根据题目意思,我们可以从第一行开始翻动棋子,由于翻动后只有第二行能影响第一行的棋子,所以用第二行维护第一行,使其全黑或全白,第三行再维护第二行,以此类推下去。
最后判断第四行棋子是否为全黑或全白。
代码如下:
下面展示一些 内联代码片
。
// A code block
var foo = 'bar';
// An highlighted block
#include<iostream>
#include<cstring>
using namespace std;
const int MAX=6;
int num[]={0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
int a[MAX],b[MAX],c[MAX],x[MAX],maxn=0x3f3f3f3f;
void wy(int a[])
{
for(x[1]=0;x[1]<=15;x[1]++)
{
c[1]=a[1]^x[1]^(x[1]>>1)^((x[1]<<1)&15);//第一行翻动后第一行的棋子状态
c[2]=a[2]^x[1];//此时第二行棋子状态
int ans=num[x[1]];//加上第一行翻动次数
for(int i=2;i<=4;i++)
{
x[i]=c[i-1];//用第i行把第i-1行变为0
ans+=num[x[i]];
c[i]=c[i]^x[i]^(x[i]>>1)^((x[i]<<1)&15);
c[i+1]=a[i+1]^x[i];
}
if(!c[4])//若第四行等于零,更新maxn取值
maxn=min(maxn,ans);
}
}
int main()
{
for(int i=1;i<=4;i++)
for(int j=0;j<4;j++)
{
char s;
cin>>s;
if(s=='b')a[i]+=(1<<j);
else b[i]+=(1<<j);
}
wy(a);
memset(c,0,sizeof(c));
wy(b);
if(maxn==0x3f3f3f3f)
cout<<"Impossible"<<endl;
else
cout<<maxn<<endl;
}