poj1753Flip Game(DFS+枚舉)

點擊打開原題鏈接

Flip Game
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 41717   Accepted: 18047

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:
  1. Choose any one of the 16 pieces.
  2. 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

題目大意:一個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");
}
 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章