poj 1753 状态压缩+bfs

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.

题目大意是给一个4*4黑白相间的棋盘,每次翻一个棋子,周围四个棋子也会随之改变状态。问最少翻几次棋盘上的颜色全部相同。

题里的棋盘只有16个格子并且只有两种颜色,很容易想到把当前棋盘压缩成一个二进制数。想到这个后题就变得很简单了,最多只有2^16种状态,跑一遍bfs就行。每次枚举翻哪个棋子,把自己和周围四个位置表示的二进制位数异或一下,如果这个状态没被访问过就加进队列,如果扫完队列也没扫到最终状态就输出impossible。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
using namespace std;
int v[100000];
int q1[100000];
int h,t;
int mi[17]={0,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768};
int main()
{
	char c;
	int a=0;
	for(int i=1;i<=4;i++)
	 for(int j=1;j<=4;j++)
	 {
	 	cin>>c;
	 	if(c=='b')a+=mi[(i-1)*4+j];
	 }
	 v[a]=1;
	 q1[++t]=a;
	 h=1;
	 if(a==0||a==65535)
	 {
	  cout<<"0";
	  return 0;
     }
	 int dis=1;
	 while(h<=t)
	 {
	 	if(dis==0)break;
	 	int w=q1[h];
	 	for(int i=1;i<=4;i++)
	 	 for(int j=1;j<=4;j++)
	 	 {
	 	 	int q=w;
			q=q^(mi[(i-1)*4+j]);
			if(i!=1)q=q^(mi[(i-2)*4+j]);
			if(j!=1)q=q^(mi[(i-1)*4+j-1]);
			if(i!=4)q=q^(mi[i*4+j]);
			if(j!=4)q=q^(mi[(i-1)*4+j+1]);
			if(q==65535||q==0)
			{
				cout<<v[w];
				dis=0;
				break;
			}
			if(v[q]==0)
			{
				v[q]=v[w]+1;
				q1[++t]=q;
			}   
		 }
		 h++;
	 }
	 if(dis==1)
	 cout<<"Impossible";
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值