Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 41717 | Accepted: 18047 |
Description
- 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.
Input
Output
Sample Input
bwwb bbwb bwwb bwww
Sample Output
4
題目大意:一個4*4的矩陣,每一格要麼是白色,要麼是黑色。現在你可以選擇任意一個格變成相反的顏色,則這個格的上,下,左,右四個格也會跟着變成相反的色(如果存在的話)。問要把矩陣的所有格子變成同一個顏色,你最少需執行幾次上面的操作。
解題思路:枚舉+dfs。一個關鍵點:對於每一格,只能翻0或1次(易證)。因此枚舉就存在2^16 =4096個狀態,最多執行16次操作,因此可行。
#include
#include
using namespace std;
char s[5][5];
bool flag=false;
int step=0;
bool judge(){
for(int i=1;i<=4;i++){
for(int j=1;j<=4;j++){
if(s[1][1]!=s[i][j]){
return false;
}
}
}
return true;
}
void change(int x,int y){
if(s[x][y]=='b') s[x][y]='w';
else s[x][y]='b';
}
void turn(int x,int y){
change(x,y);
if(x-1>0)change(x-1,y);
if(x+1<5)change(x+1,y);
if(y-1>0)change(x,y-1);
if(y+1<5)change(x,y+1);
}
void dfs(int x,int y,int deep){
if(deep==step){
flag=judge();
return;
}
if(x>4||flag){
return;
}
turn(x,y);
if(y==4){
dfs(x+1,1,deep+1);
turn(x,y);
dfs(x+1,1,deep);
}
else{
dfs(x,y+1,deep+1);
turn(x,y);
dfs(x,y+1,deep);
}
return;
}
int main(){
for(int i=1;i<=4;i++){
for(int j=1;j<=4;j++){
scanf("%c",&s[i][j]);
}
getchar();
}
for(step=0;step<17;step++){
dfs(1,1,0);
if(flag==true){
break;
}
}
if(flag==true){
printf("%d\n",step);
}
else
printf("Impossible\n");
}