#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXN (15+5)
#define INF 0x7f7f7f7f
int n, tot;
int fx[4][2] = {{-1,0}, {0,-1}, {1,0}, {0,1}};
int read[MAXN][MAXN], now_f[MAXN][MAXN];
int ans, ans_c, ans_f = INF;
bool diff(int a, int b){
if(a != b) ans_c++;
if(!a && b) return false;
return true;
}
void add(int a, int b){
if(a < 0 || a > n || b < 0 || b > n) return;
tot += now_f[a][b];
}
bool check(){
tot = 0;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++){
int tot = 0;
for(int k = 0; k < 4; k++){
int x = i+fx[i][0], y = i+fx[i][1];
add(x, y);
}
if(tot%2) return false;
}
return true;
}
void work(){
ans_c = ans;
for(int i = 2; i <= n; i++){
int tmp = i>2? now_f[i-2][1]: 0;
if((now_f[i-1][2]+tmp) % 2) now_f[i][1] = 1;
else now_f[i][1] = 0;
if(!diff(now_f[i][1], read[i][1])) return;
tmp = i>2? now_f[i-2][n]: 0;
if((now_f[i-1][n-1]+tmp) % 2) now_f[i][n] = 1;
else now_f[i][n] = 0;
if(!diff(now_f[i][n], read[i][n])) return;
for(int j = 2; j < n; j++){
tmp = now_f[i-1][j-1] + now_f[i-1][j+1];
tmp += i>2? now_f[i-2][j]: 0;
if(tmp%2) now_f[i][j] = 1;
else now_f[i][j] = 0;
if(!diff(now_f[i][j], read[i][j])) return;
}
}
if(check()) ans_f = min(ans_f, ans_c);
}
void dfs(int now){
if(now > n){
work();
return;
}
bool ok = false;
now_f[1][now] = 0;
if(!read[1][now]) dfs(now+1);
now_f[1][now] = 1;
if(!read[1][now]) ans++, ok = true;
dfs(now+1);
if(ok) ans--, ok = false;
}
int main(){
int T;
scanf("%d", &T);
int t = 0;
while(T--){
scanf("%d", &n);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++) scanf("%d", &read[i][j]);
ans = 0; ans_f = INF;
dfs(1);
if(ans_f != INF) printf("Case %d: %d\n", ++t, ans_f);
else printf("Case %d: -1\n", ++t);
}
return 0;
}
uva 11464
最新推荐文章于 2018-09-21 13:09:51 发布