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
Output for Sample Input
解题报告:题目大意有一个N×N的矩阵,矩阵中的元素只有1或0,如果说对于一个矩阵,它的所有的点的上下左右的点的和是偶数,则称这个矩阵为偶数矩阵,现在给你一个任意的矩阵,要求的是如果要把这个矩阵变成偶数矩阵的话,最少需要将多少个点由1变成0,若不存在话,输出-1.(N<=15)
先分析时间复杂度。 由题目可知矩阵的最大的行数为15,那么我们最容易想到就是去枚举每一个位置的数,那么矩阵的最多的元素为255,那么255个元素的状态为2^255,很明显这个是不可能实现的。
那么我们相到第一行的状态最多为2^15的,那么我们知道如果一个矩阵满足题目要求的话就是每一个元素的周围四个元素之和为偶数,那么我们就可以通过第一行求出第二行,利用第二行求出第三行…
那么我们只要去枚举第一行的2进制的每一个值,然后判断即可。
07 | const int INF = 1<<30; |
11 | int solve( int n , int s){ |
13 | memset (tmp , 0 , sizeof (tmp)); |
14 | for ( int i = 0 ; i < n ; i++){ |
21 | for ( int i = 1 ; i < n ; i++){ |
22 | for ( int j = 0 ; j < n ; j++){ |
33 | if (tmp[i][j] == 0 && m[i][j] == 1) |
39 | for ( int i = 0 ; i < n ; i++) |
40 | for ( int j = 0 ; j < n ; j++) |
41 | if (m[i][j] != tmp[i][j]) |
47 | int Case , n , cnt = 1; |
51 | for ( int i = 0 ; i < n ; i++) |
52 | for ( int j = 0 ; j < n ; j++) |
53 | scanf ( "%d" , &m[i][j]); |
55 | for ( int i = 0 ; i < (1<<n) ; i++) |
56 | ans = min(ans , solve(n , i)); |
57 | printf ( "Case %d: %d\n" , cnt++ , ans == INF ? -1 : ans); |