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