POJ1753 Flip Game(开关问题) 深搜

题目传送门

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的棋盘,棋盘上分别有黑白棋子,你可以对棋子进行翻转操作,在一次操作中会将棋子本身以及上下左右的棋子同时翻转(如果存在棋子),即黑变白白变黑,问你这个棋盘是否存在一种操作可以使得棋盘最终变为只有一种颜色的棋子。

思路:根据题意可知翻转次序和最终结果无关,因为无论次序如何,某个点的翻转次数是不变的,最终结果也不变,所以可以暴力搜索解决本题。对于每一点可以选择翻转或者不翻转,用dfs深搜的同时检查是否已经符合,符合则更新答案并且返回。

AC代码

#include<iostream>
using namespace std;
const int maxn=10;
int a[maxn][maxn],flag=0,mi=0x3f3f3f3f;
char ch; 
void turn(int x,int y){ //翻转函数 
	a[x][y]=1-a[x][y];
	a[x+1][y]=1-a[x+1][y];
	a[x-1][y]=1-a[x-1][y];
	a[x][y+1]=1-a[x][y+1];
	a[x][y-1]=1-a[x][y-1];
}
bool check(){ //检查函数 
	int cnt=0; //count
	for(int i=1;i<=4;i++){
		for(int j=1;j<=4;j++){
			if(a[i][j]) cnt++;
		}
	}
	if(cnt==0||cnt==16) return 1;
	else return 0;
}
void dfs(int x,int y,int t){
	if(check()){ //检查是否已经符合要求 
		mi=min(mi,t); flag=1; 
		return ;
	}
	if(x>4){ //剪枝,如果已经判断过最后一个点即(4,4) 
		return ; 
	}
	//这里我用从上到下,从第一列到最后一列的顺序,本题结果和翻转次序无关 
	int xx=x;
	int yy=y+1;
	if(yy>4){
		yy=1; xx++;
	}
	
	dfs(xx,yy,t);//不翻转直接下一步 
	turn(x,y); //翻转这个棋子 
	dfs(xx,yy,t+1);
	turn(x,y); //翻转回来 
} 
signed main()
{
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); 
	for(int i=1;i<=4;i++){
		for(int j=1;j<=4;j++){
			cin>>ch;
			if(ch=='b'){
				a[i][j]=1; //赋值为0和1方便后续操作 
			}
		}
	}
	if(check()){ //判断初始时是否就已经符合要求 
		cout<<0<<endl;
		return 0;
	}
	dfs(1,1,0); //从(1,1)开始,初始化操作0次 
	if(flag){ //如果有操作可以达到要求 
		cout<<mi;
	}
	else{
		cout<<"Impossible";
	}
	return 0;
}
 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值