POJ 1753(Flip Game)

tips:
1、对于每个棋子,翻转偶数次相当于原封不动,翻转奇数次相当于翻转一次
2、总共有16个棋格子,利用组合数(关键就是“从16个格子里面任意选取n个元素的所有组合”如何实现:DFS),共 2^16 种不同翻转选择


#include<iostream>
using namespace std;
int a[16], b[16];
bool achieve = false;
int result[16]; //存储某个可能的组合情况

bool check(int a[]) //检查是否全黑或全白
{
	bool all = true;
	for (int i = 1; i < 16; ++i)	if (a[i] != a[0]) all = false;
	return all;
}

void flip(int a[], int i)
{
	a[i] ^= 1;
	int m = i % 4, n = i / 4;
	if (m > 0) a[i - 1] ^= 1;
	if (m < 3) a[i + 1] ^= 1;
	if (n > 0) a[i - 4] ^= 1;
	if (n < 3) a[i + 4] ^= 1;
}

void DFS(int a[], int start, int a_len, int *result, int count, int num)
{
	for (int i = start; i < a_len + 1 - count; ++i)
	{
		result[count - 1] = i;
		if (count == 1)
		{
			for (int i = 0; i < 16; i++) b[i] = a[i]; //数组b作为数组a的副本
			for (int j = num - 1; j >= 0; --j)
			{
				flip(b, result[j]);
			}
			if (check(b)) achieve = true;
		}
		else DFS(a, i + 1, a_len, result, count - 1, num);
	}
}
int main(void)
{
	char t;
	//因为该棋盘的规模已知,且比较小,所以可以逐个字符输入,不会TLE
	//不过最好逐行字符串输入,保证不会TLE
	for (int i = 0; i < 16; ++i)
	{
		cin >> t;
		if (t == 'w') a[i] = 1;
		else a[i] = 0;
	}
	if (check(a)) cout << 0 << endl;
	else
	{
		for (int i = 1; i <= 16; ++i) //翻转1~16个棋子的各个情况都尝试一下
		{
			DFS(a, 0, 16, result, i, i);
			if (achieve)
			{
				cout << i << endl;
				break;
			}
		}
		if (!achieve) cout << "Impossible" << endl;
	}
	return 0;
}


//字符串输入版本

#include<iostream>
using namespace std;
int a[16], b[16];
bool achieve = false;
int result[16];

bool check(int a[])
{
	bool all = true;
	for (int i = 1; i < 16; ++i)	if (a[i] != a[0]) all = false;
	return all;
}

void flip(int a[], int i)
{
	a[i] ^= 1;
	int m = i % 4, n = i / 4;
	if (m > 0) a[i - 1] ^= 1;
	if (m < 3) a[i + 1] ^= 1;
	if (n > 0) a[i - 4] ^= 1;
	if (n < 3) a[i + 4] ^= 1;
}

void DFS(int a[], int start, int a_len, int *result, int count, int num)
{
	for (int i = start; i < a_len + 1 - count; ++i)
	{
		result[count - 1] = i;
		if (count == 1)
		{
			for (int i = 0; i < 16; i++) b[i] = a[i]; 
			for (int j = num - 1; j >= 0; --j)
			{
				flip(b, result[j]);
			}
			if (check(b)) achieve = true;
		}
		else DFS(a, i + 1, a_len, result, count - 1, num);
	}
}
int main(void)
{
	char str[5][5]; //数组开大些,不能开成str[4][4],因为输入的每个字符串末尾有空字符'\0'
	int len = 4;
	for (int i = 0; i < 4; i++) cin >> str[i];
	for (int i = 0; i < 4; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			if (str[i][j] == 'w') a[i * 4 + j] = 1;
			else a[i * 4 + j] = 0;
		}
	}
	if (check(a)) cout << 0 << endl;
	else
	{
		for (int i = 1; i <= 16; ++i) 
		{
			DFS(a, 0, 16, result, i, i);
			if (achieve)
			{
				cout << i << endl;
				break;
			}
		}
		if (!achieve) cout << "Impossible" << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值