95. 费解的开关
题目链接https://www.acwing.com/problem/content/description/97/
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int n;
char c[10][10];
int a[10][10], b[10][10];
int ans = 10, minn;
bool fw(int x, int y) {
return x >= 0 && x <= 4 && y >= 0 && y <= 4;
}
void change(int x, int y) {
a[x][y] = (a[x][y] + 1) % 2;
if (fw(x - 1, y)) a[x - 1][y] = (a[x - 1][y] + 1) % 2;
if (fw(x, y - 1)) a[x][y - 1] = (a[x][y - 1] + 1) % 2;
if (fw(x, y + 1)) a[x][y + 1] = (a[x][y + 1] + 1) % 2;
if (fw(x + 1, y)) a[x + 1][y] = (a[x + 1][y] + 1) % 2;
}
void steal() {
memcpy(b, a, sizeof(a));
for (int i = 0; i < (1 << 5); i++) {
int x=i;
ans = 0;
memcpy(a, b, sizeof(b));
for (int j = 0; j < 5; j++) {
if ((x >> j) & 1)
change(0, j), ans++;
}
for (int j = 0; j < 4; j++) {
if (ans > 6)
break;
for (int k = 0; k < 5; k++) {
if (a[j][k] == 0)
change(j + 1, k), ans++;
}
}
if (ans > 6)
continue;
bool flag = 1;
for (int j = 0; j < 5; j++) {
if (a[4][j] == 0) flag = 0;
}
if (flag)
minn = min(minn, ans);
}
}
int main() {
cin >> n;
while (n--) {
for (int i = 0; i < 5; i++)
cin >> c[i];
minn = 10;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
a[i][j] = c[i][j] - '0';
}
}
steal();
if (minn == 10)
cout << "-1" << endl;
else
cout << minn << endl;
}
return 0;
}