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).
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.
#include<iostream>
using namespace std;
int source[4][4];
int tempSource[4][4];
void changeIJ(int i,int j){
tempSource[i][j] = -tempSource[i][j];
if(i-1 >= 0){
tempSource[i-1][j] = -tempSource[i-1][j];
}
if(j-1 >= 0){
tempSource[i][j-1] = -tempSource[i][j-1];
}
if(i+1 < 4){
tempSource[i+1][j] = -tempSource[i+1][j];
}
if(j+1 < 4){
tempSource[i][j+1] = -tempSource[i][j+1];
}
}
int main(){
char temp;
int result = 20;
for(int i = 0; i <4; i++){
for(int j = 0; j <4; j++){
cin>>temp;
if(temp == 'b'){
source[i][j] = -1;
}else{
source[i][j] = 1;
}
}
}
for(int b = -1; b <= 1; b = b+2){
int cases = 0;
while(cases < 16){
int tempResult = 0;
int i = 0;
for(int i = 0; i <4; i++){
for(int j = 0; j <4; j++){
tempSource[i][j] = source[i][j];
}
}
//使用&运算 取出各位的数值
int mask = 1;
int shift = 0;
while(mask < 9){
int tempBit = mask & cases;
if(tempBit >= 1){
changeIJ(0,shift);
tempResult++;
}
mask = mask << 1;
shift = shift+1;
}
for(int i = 0;i < 3; i++){
for(int j = 0; j <4; j++){
if(tempSource[i][j] == -1*b){
changeIJ(i+1,j);
tempResult++;
}
}
}
//检查
int j = 0;
for(;j < 4; j++){
if(tempSource[3][j] == -1*b){
break;
}
}
if(j == 4){
if(tempResult < result){
result = tempResult;
}
}
cases++;
}
}
if(result == 20){
cout<<"Impossible"<<endl;
}else{
cout<<result<<endl;
}
}

本文介绍了一个名为Flipgame的游戏,该游戏在一个4x4的棋盘上进行,棋盘上的每个方格都放置了一枚两面分别为黑白的棋子。文章详细阐述了游戏规则,并提供了一段C++代码,用于寻找将所有棋子翻转到同一面所需的最少轮数。
658

被折叠的 条评论
为什么被折叠?



