Poj 1753 Flip Game

本文介绍了一种使用广度优先搜索(BFS)和位运算来解决Flipgame的算法。目标是在最少的步骤内将所有棋子翻转至同一面。通过枚举16种可能的情况并进行剪枝,算法有效地找到了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

时隔四年重新开始刷poj,还是原来的味道,爷青回hhhh

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.

bfs枚举16种情况,并通过位运算记录每种情况剪枝

#include<iostream>
#include<limits.h>
#include<string.h>
using namespace std;
bool mi[65536];
bool is_end(int status,int step){
	if (status==0||status==65535) {
		cout<<step<<endl;
		return(true);
	}
	else return(false);
}
int work2(int n,int status){
	if(0<=n&&n<=15){
		int tt=1<<n;
		return(status^tt);
	}
	else return(status);
}
int work(int n,int status){
	int temp=status;
	temp=work2(n-4,temp);
	if(1<=n%4&&n%4<=3) temp=work2(n-1,temp);temp=work2(n,temp);if (0<=n%4&&n%4<=2) temp=work2(n+1,temp);
	temp=work2(n+4,temp);
	return(temp);
}
void bfs(int status){
	int head=0,tail=0,temp,step,temp_status;
	int que1[65536],que2[65536];
	bool t1=true;
	que1[0]=status;que2[0]=0;
	while (head<=tail){
		temp=que1[head];
		step=que2[head];
		head++;
		for (int i=0;i<16;i++){
			temp_status=work(i,temp);		
			if (!mi[temp_status]){
				mi[temp_status]=true;
				tail++;
				que1[tail]=temp_status;
				que2[tail]=step+1;
			}
			if (is_end(temp_status,step+1)) {
				t1=false;
				break;
			}
		}
		if (!t1) break; 
	}
	if (t1) cout<<"Impossible"<<endl;
}
int main(){
	int status=0;
	char ch;
	memset(mi,sizeof(mi),false);
	for(int i=0;i<16;i++){
		cin>>ch;
		status=status<<1;
		status+=(ch=='b');
	}
	mi[status]=true;
	if (!is_end(status,0)) bfs(status);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值