记得每组数据,用memset初始化下数组,不然会WA
#include <cstdio>
#include <algorithm>
#include <cstring>
#define INF 1000000000
using namespace std;
int a[20][20],b[20][20];
int n;
int res = 0;
int curCnt = 0;
bool isok = false;
int numberNeed(int i,int j) {
int cnt = b[i-1][j]+b[i][j-1]+b[i][j+1];
if(cnt%2==0)
return 0;
return 1;
}
void DFS(int dep) {
if(dep > n) {
int temp = curCnt;
for(int i = 2;i <= n;i++)
for(int j = 1;j <= n;j++) b[i][j] = a[i][j];
for(int i = 2;i <= n;i++)
for(int j = 1;j <= n;j++) {
b[i][j] = a[i][j];
int need = numberNeed(i-1,j);
if(a[i][j] == need)
continue;
else {
if(need==0) {
i = j = 100;
curCnt = INF;
} else {
b[i][j] = 1;
curCnt++;
}
}
if(curCnt != INF)
isok = true;
res = min(curCnt,res);
curCnt = temp;
return;
}
if(a[1][dep] == 1)
DFS(dep+1);
else {
DFS(dep+1);
curCnt += 1;
b[1][dep] = 1;
DFS(dep+1);
b[1][dep] = 0;
curCnt--;
}
}
int main() {
// freopen("out.txt","w",stdout);
int T;
int Case = 1;
scanf("%d",&T);
while(T--) {
isok = false;
curCnt = 0;
res = INF;
scanf("%d",&n);
memset(b,0,sizeof(b));
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++) {
scanf("%d",&a[i][j]);
b[i][j] = a[i][j];
}
DFS(1);
printf("Case %d: ",Case++);
if(isok) {
printf("%d\n",res);
} else {
printf("-1\n");
}
}
return 0;
}