例题:Flip Game
#include <iostream>
#include <algorithm>
#include <map>
#include <cstdio>
using namespace std;
#define ll long long
const int INF = 0x3f3f3f3f; ///1 061 109 567
const int negative_infinite = 0xcfcfcfcf; ///-808 464 433
const ll mod = 1e9 + 7;
const double eps = 1e-8;
const int MAXN = 1e6 + 117;
const int MAXM = 1e6 + 117;
int ans;
int a[7][7];
char s[7][7];
bool check() {
for(int i = 1; i <= 4; i++)
for(int j = 1; j <= 4; j++)
if(a[i][j] != a[1][1])
return false;
return true;
}
void change(int i, int j) {
a[i][j] ^= 1; //做异或处理
a[i + 1][j] ^= 1;
a[i - 1][j] ^= 1;
a[i][j - 1] ^= 1;
a[i][j + 1] ^= 1;
}
void dfs(int x, int cnt) {
if(x == 16) { //出口
if(check())
ans=min(ans,cnt);
return;
}
dfs(x+1,cnt); //从末尾开始
change(x/4+1,x%4+1);
dfs(x+1,cnt+1);
change(x/4+1,x%4+1); //注意还原!当前状态不能影响之前的状态
//一维数组映射为二维数组
} //x/m+1 为行数 x%m+1为列数
int main() {
for(int i = 0; i < 4; i++)
scanf("%s", s[i]);
for(int i = 1; i <= 4; i++)
for(int j = 1; j <= 4; j++)
if(s[i - 1][j - 1] == 'b')
a[i][j] = 1;
ans = INF;
dfs(0, 0);
if(ans == INF)
puts("Impossible");
else
printf("%d\n", ans);
return 0;
}