Flip Game
Time Limit: 1000MS | Memory Limit: 65536K |
Total Submissions: 45588 | Accepted: 19531 |
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.
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
題意: 一個棋盤上有黑白兩種棋子,flip一顆棋子,它本身和它四周的棋子都變為相反的顔色。求最少要幾步才能使棋盤上的棋子顔色全部一樣。
題解: 用dfs。逐點搜尋,每搜到一個點就有兩種狀态,flip這個棋子或者不flip這個棋子。如果flip這個棋子,則step+1,再搜下一個點;否則step不變,直接搜下一個點。而計算下一個點的坐标可以用公式:ty=(y*4+x+1)/4; tx=(y*4+x+1)%4; 也就是先将坐标一維展開,+1,再轉化成二維。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char str[5][5];
int map[4][4],minn;
void reverse(int y,int x)
{
if(y-1>=0)
map[y-1][x]=!map[y-1][x];
if(x-1>=0)
map[y][x-1]=!map[y][x-1];
if(y+1<4)
map[y+1][x]=!map[y+1][x];
if(x+1<4)
map[y][x+1]=!map[y][x+1];
map[y][x]=!map[y][x];
}
int check()
{
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
if(map[i][j]!=map[0][0])
return 0;
return 1;
}
void dfs(int y,int x,int step)
{
int ty=(y*4+x+1)/4;
int tx=(y*4+x+1)%4;
if(y==4)
{
if(check())
minn=min(minn,step);
return ;
}
reverse(y,x);
dfs(ty,tx,step+1);
reverse(y,x);
dfs(ty,tx,step);
}
int main()
{
while(~scanf("%s",str[0]))
{
for(int i=1; i<4; i++)
scanf("%s",str[i]);
for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
{
if(str[i][j]=='b')
map[i][j]=1;
else
map[i][j]=0;
}
}
minn=9999;
dfs(0,0,0);
if(minn<=16)
printf("%d\n",minn);
else
printf("Impossible\n");
}
return 0;
}