You are given an N * N binary matrix 'MAT'. You can do two operations in the matrix:
i) Swap any two rows.
ii) Swap any two columns.
Your task is to find the minimum number of operations needed to convert this matrix into a chessboard matrix.
If the task is impossible print -1.
Note:
A chessboard matrix is a binary matrix where there are no two 0’s and no two 1’s who are adjacent to each other.
For example:
[ [1, 0], [0, 1] ] and [ [0, 1], [1, 0] ] are chessboard matrix whereas [ [1,0], [1, 1] ] isn’t.
The first line of the input contains ‘T’, denoting the number of test cases.
The first line of each test case contains an integer, ‘N’ denoting dimensions of the matrix.
Next ‘N’ lines contains, N space-separated integers MAT[i][j].
Output Format:
For each test case, print the minimum number of operations to convert the given matrix into a chessboard matrix.
Note:
Don't print anything it has already been taken care of. Just implement the given function.
1 <= T <= 3
1 <= N <= 3000
0 <= MAT[i][j] <= 1
Time Limit: 1sec
2
4
0 1 1 0
0 1 1 0
1 0 0 1
1 0 0 1
2
1 0
1 0
2
-1
In test case 1:
Swap column 1 and column 2.
| 0 1 1 0 | | 1 0 1 0 |
| 0 1 1 0 | = | 1 0 1 0 |
| 1 0 0 1 | | 0 1 0 1 |
| 1 0 1 1 | | 0 1 0 1 |
Swap row 2 and row 3.
| 1 0 1 0 | | 1 0 1 0 |
| 1 0 1 0 | = | 0 1 0 1 |
| 0 1 0 1 | | 1 0 1 0 |
| 0 1 1 1 | | 0 1 0 1 |
Minimum 2 operations are required for the transformation.
In test case 2, It is impossible to convert the matrix into a chessboard matrix.
2
6
0 0 1 1 0 1
1 1 0 0 1 0
1 1 0 0 1 0
0 0 1 1 0 1
0 0 1 1 0 1
1 1 0 0 1 0
4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1
2
0
In the first test case, we need two operations to convert it into required chessboard matrix.
In the second test case, the given matrix is required matrix only.
There are only two possible unique rows and columns, where one is an inversion of the other.
Explanation:
Algorithm is as follows:
O( N^2 ), where N is the dimension of the matrix
We need to iterate over the whole matrix, thus time complexity is O(N^2)
O(1)
No additional memory is required.