描述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).
输入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).题意:给你一张4*4的方格,每个格子里都有一枚两面分别为黑白两色的棋子,每个棋子一开始的状态不一样,每次 操作一个棋子,可以使该棋子与其周边棋子翻面,问你需要最少多少次操作才可以使所有棋子颜色一样(可以是黑色,也可以是白色)。
这道题我们采用二进制枚举,枚举所有可能的操作情况,然后比较输出最小的方案即可。
话不多说,看代码
#include <iostream>
#include <cstdio>#include <cstring>#include <cmath>using namespace std;char ch[10][10];int a[10][10],t[10][10];int b[17];int ans=16;bool found=false;void fan(int r,int c){ t[r][c]=!t[r][c]; t[r-1][c]=!t[r-1][c]; t[r][c+1]=!t[r][c+1]; t[r+1][c]=!t[r+1][c]; t[r][c-1]=!t[r][c-1];} int main(){ std::ios::sync_with_stdio(false); for(int i=1;i<=4;i++) for(int j=1;j<=4;j++) { cin>>ch[i][j]; if(ch[i][j]=='w')a[i][j]=0; if(ch[i][j]=='b')a[i][j]=1; } int sum=0; for(int i=1;i<=4;i++) for(int j=1;j<=4;j++) sum+=a[i][j]; if(sum==0||sum==16)//如果一开始就不用操作,直接输出 { cout<<0<<endl; return 0; } while(b[0]!=1) { for(int i=1;i<=4;i++) for(int j=1;j<=4;j++) t[i][j]=a[i][j]; int cnt=0; for(int i=1;i<=16;i++) { if(b[i]==1) { int r=(ceil)(i/4.0);//计算行 int c=(i%4==0?i%4+4:i%4);计算列 fan(r,c);//操作 cnt++;//计数 } } sum=0; for(int i=1;i<=4;i++) for(int j=1;j<=4;j++) sum+=t[i][j]; if(sum==0||sum==16) //如果成功,就进行比较,取较小的;found放成true. { found=true; if(cnt<ans)ans=cnt; } int k=16; while(b[k]!=0)k--; b[k]=1; for(int i=k+1;i<=16;i++)b[i]=0;//二进制枚举 } if(!found) cout<<"Impossible"<<endl;//没有这种情况 else cout<<ans<<endl; return 0; }