We have a grid of size N x N. Each cell of the grid initially contains a zero(0) or a one(1).
The parity of a cell is the number of 1s surrounding that cell. A cell is surrounded by at most 4 cells (top, bottom, left, right).
Suppose we have a grid of size 4 x 4:
1 | 0 | 1 | 0 | The parity of each cell would be | 1 | 3 | 1 | 2 |
1 | 1 | 1 | 1 | 2 | 3 | 3 | 1 | |
0 | 1 | 0 | 0 | 2 | 1 | 2 | 1 | |
0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
For this problem, you have to change some of the 0s to 1s so that the parity of every cell becomes even. We are interested in the minimum number of transformations of 0 to 1 that is needed to achieve the desired requirement.
Input
The first line of input is an integer T (T<30) that indicates the number of test cases. Each case starts with a positive integer N(1≤N≤15). Each of the next N lines contain N integers (0/1) each. The integers are separated by a single space character.
Output
For each case, output the case number followed by the minimum number of transformations required. If it's impossible to achieve the desired result, then output -1 instead.
Sample Input
3
3
0 0 0
0 0 0
0 0 0
3
0 0 0
1 0 0
0 0 0
3
1 1 1
1 1 1
0 0 0
Output for Sample Input
Case 1: 0
Case 2: 3
Case 3: -1
这个问将所给m*n的01矩阵,需要求出最少将0变成1的次数,使得所有点的上下左右之和为偶数。有题目的要求可以知道如果对整个地图用DFS的话会超时,而且超时会很严重,而通过观察可以发现后面的几行可以由第一行递推得出。
解法:
首先用DFS枚举第一行的所有情况,然后对每种情况进行递推后面的变化情况,然后取最小即可。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
const int maxn=20;
const int INF=100000000;
int n,A[maxn][maxn],B[maxn][maxn];
int ans=INF,tmp=INF;
void solve()
{
for(int i=0;i<n;i++){//由第一行生成符合题设的矩阵,使得每个元素的上下左右之后为偶数
for(int j=0;j<n;j++){
int sum=0;
if(i-1>=0)
sum+=B[i-1][j];
if(j-1>=0)
sum+=B[i][j-1];
if(j+1<n)
sum+=B[i][j+1];
if(sum%2==0)
B[i+1][j]=0;
else
B[i+1][j]=1;
}
}
int cnt=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(A[i][j]!=B[i][j]){
if(A[i][j]==1)//因为题设要求只能将0变成1,所以如果将1变成0了,这种矩阵是不符合题设的
cnt=INF;
else
cnt++;
}
}
}
tmp=cnt;
return;
}
void dfs(int num)//生成第一行所有情况,并求出最小值
{
if(num==n){
solve();
ans=min(ans,tmp);
return;
}
else{
B[0][num]=1;
dfs(num+1);
B[0][num]=0;
dfs(num+1);
}
return;
}
int main(){
int t;
scanf("%d",&t);
int case1=1;
while(case1<=t){
int r;
ans=INF;
scanf("%d",&n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d",&A[i][j]);
}
}
dfs(0);
if(ans<INF)
printf("Case %d: %d\n",case1,ans);
else
printf("Case %d: -1\n",case1);
case1++;
}
return 0;
}