题意:
一个n*n矩阵(由0/1组成),将尽量少的0变成1,使得每个元素上下左右(有的画)的元素之和为偶数,求改变的元素的最小个数,无解则输出-1;
思路:
枚举第一行(最多为15),一次由上一行计算出下一行,比较,求得最小个数
代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
#define Max 0x3f3f3f3f
int n;
int Start[20][20],End[20][20];
int solve(int k) {
memset(End, 0, sizeof(End));
int i, j;
for (i = 0; i < n; i++) {
if (k & (1 << i))
End[0][i] = 1;
else if (Start[0][i] == 1)
return Max;
}
for (i = 1; i < n; i++) {
for (j = 0; j < n; j++) {
int sum = 0;
//枚举三个方向,上左右,得出该坐标值
if (i > 1)
sum += End[i - 2][j];
if (j > 0)
sum += End[i-1][j-1];
if (j < n - 1)
sum += End[i - 1][j + 1];
End[i][j] = sum % 2;
if (Start[i][j] == 1 && End[i][j] == 0)
return Max;
}
}
int cnt=0;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (Start[i][j] != End[i][j])
cnt++;
return cnt;
}
int main() {
int Case;
int index = 0;
scanf("%d", &Case);
while (Case--) {
scanf("%d", &n);
int i, j;
for ( i = 0; i<n; i++)
for ( j = 0; j<n; j++)
scanf("%d", &Start[i][j]);
int cnt = Max;
int m = 1 << n;
for (i = 0; i < m; i++)
cnt = min(cnt, solve(i));
printf("Case %d: ", ++index);
if (cnt == Max)
printf("-1\n");
else
printf("%d\n", cnt);
}
return 0;
}