题目链接
思路: 4×4的矩阵只有16个状态,每个状态都是只有开和关两种状态,因此16位二进制可以将所有状态进行表示出来,每次进行判断即可,具体见代码。
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int n;
char g[5][5], back[5][5];
void turnone (int x, int y)
{
if (g[x][y] == '-') g[x][y] = '+';
else g[x][y] = '-';
}
void turn (int x, int y)
{
for (int i = 0; i < 4; i ++)
turnone (x, i);
for (int i = 0; i < 4; i ++)
turnone (i, y);
turnone (x, y);
}
bool check ()
{
for (int i = 0; i < 4; i ++)
for (int j = 0; j < 4; j ++)
if (g[i][j] == '+')
return false;
return true;
}
int main ()
{
ios::sync_with_stdio (false);
cin.tie (0); cout.tie(0);
for (int i = 0; i < 4; i ++) cin >> g[i];
int res = 1e8, path;
for (int i = 0; i < 1 << 16; i ++)
{
int step = 0;
memcpy (back, g, sizeof back);
for (int j = 0; j < 16; j ++)
{
if (i >> j & 1)
{
int x = j / 4, y = j % 4;
turn (x, y);
step ++;
}
}
if (check())
{
if (step < res)
{
res = step;
path = i;
}
}
memcpy (g, back, sizeof back);
}
cout << res << "\n";
for (int i = 0; i < 16; i ++)
if (path >> i & 1)
cout << i / 4 + 1 << " " << i % 4 + 1<< "\n";
return 0;
}