程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> POj 1753--Flip Game--位運算+BFS

POj 1753--Flip Game--位運算+BFS

編輯:C++入門知識

POj 1753--Flip Game--位運算+BFS


Flip Game Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 30669 Accepted: 13345

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

Source

我不得不說位運算是一個強大的東西,之前從來沒怎麼用過,沒想到這麼一道本來沒有頭緒的題,位運算一優化成了一道裸一維的BFS,說這個題目,大意是一個翻牌游戲,牌有黑白兩面,當翻到所有的牌都是黑或都是白時,滿足狀態,輸出最小操作步數。每個位置的牌的都可以翻,但如過翻了當前這張牌,它的相鄰的位置的牌都要翻過來。對於所有的狀態,一共有2^16種(4*4的圖)
而對於翻牌操作,假設當前狀態為s 想要翻第i個位置的牌,只要s^=1<
#include 
#include 
#include 
using namespace std;
bool vis[70000];
char ma[20];
typedef struct node
{
	int state,step;
};
void bfs(int s)
{
	queue  Q;
	node t;t.state=s;t.step=0;
	vis[s]=1;
	Q.push(t);
	while(!Q.empty())
	{
		node v=Q.front();Q.pop();
		if(v.state==0||v.state==65535)
		{
			cout<=0) tem^=1<<(i-4);//上
			if(i<12) tem^=1<<(i+4);//下
			if(i%4!=0) tem^=1<<(i-1);//左
			if((i+1)%4!=0) tem^=1<<(i+1);//右
			if(!vis[tem])
			{
				vis[tem]=1;
				t.state=tem;
				t.step=v.step+1;
				Q.push(t);
			}
		}
	}
	puts("Impossible");
}
int main()
{
	int i=0,s=0;
	memset(vis,0,sizeof(vis));
	while(i<16)
	{
		cin>>ma[i];
		if(ma[i]=='b')
			s+=1<




  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved