很早的题,今天终于AC了。
分黑白两种情况枚举第一行,与Fliptile类似。
#include <iostream>
#include <cstdio>
#include <cstring>
#define min(a,b) (((a) < (b)) ? (a) : (b))
using namespace std;
const int MAX = 4;
const int SUP = 16;
bool board[MAX+2][MAX+2];
bool temp_board[MAX+2][MAX+2];
int ans;
int step;
char readchar()
{
char t;
while (t = getchar())
{
if (t == 'b' || t == 'w')
return t;
}
}
void read_board()
{
for (int i = 1; i <= MAX; i++)
for (int j = 1; j <= MAX; j++)
board[i][j] = (readchar() == 'b') ? 1 : 0;
}
const int ROW[] = {0, 0, 0, 1, -1};
const int COL[] = {0, 1, -1, 0, 0};
void _flip(int r, int c)
{
for (int i = 0; i < 5; i++)
temp_board[r+ROW[i]][c+COL[i]] = !temp_board[r+ROW[i]][c+COL[i]];
}
void _operate(int ord, int aim)
{
for (int j = 1; j <= MAX; j++)
{
if (ord & 1)
{
_flip(1, j);
step++;
}
ord >>= 1;
}
for (int i = 2; i <= MAX; i++)
for (int j = 1; j <= MAX; j++)
{
if (temp_board[i-1][j] != aim)
{
_flip(i, j);
step++;
}
}
}
bool is_ok(int aim) // all zeros or not
{
for (int j = 1; j <= MAX; j++)
if (temp_board[MAX][j] != aim)
return false;
return true;
}
int main()
{
// input
read_board();
// enumberate
ans = SUP;
for (int aim = 0; aim <= 1; aim++)
{
int sz = 1 << MAX;
for (int i = 0; i < sz; i++)
{
step = 0;
memcpy(temp_board, board, sizeof(board));
_operate(i, aim);
if (is_ok(aim))
ans = min(ans, step);
}
}
if (ans != SUP)
printf("%d", ans);
else
printf("Impossible");
return 0;
}