#K65287. Magic Matrix Transformation
Magic Matrix Transformation
Magic Matrix Transformation
You are given a grid of integers with n rows and m columns. Your task is to determine if by performing swaps of any two elements, the grid can be rearranged into a magic matrix.
A magic matrix is defined as a matrix where every row and every column contains the exact same multiset of elements. In other words, if we denote \(r_i\) as the multiset of elements in the i-th row and \(c_j\) as the multiset of elements in the j-th column, then for a magic matrix it must hold that:
\[ \forall i:\; sort(r_i)=sort(r_1) \quad \text{and} \quad \forall j:\; sort(c_j)=sort(c_1). \]
You are not required to compute the actual minimum number of swaps if the grid is not already a magic matrix. Simply check if the grid already satisfies the magic matrix condition. If it does, output 0
; otherwise, output -1
.
Note: The operation allowed is swapping any two elements of the matrix. However, determining the minimal number of swaps to convert a non-magic matrix to a magic one is a complex (NP-hard) problem. Therefore, in this problem, if the grid is not already a magic matrix, you should output -1
.
inputFormat
The input is given in the following format from standard input:
T n m row1 row2 ... rown ... (repeated T times)
Where:
T
is the number of test cases.- For each test case, the first line contains two integers
n
andm
describing the dimensions of the grid. - Then,
n
lines follow, each containingm
space-separated integers representing a row of the grid.
outputFormat
For each test case, output a single integer on a new line from standard output. This integer is 0
if the given grid is already a magic matrix, and -1
otherwise.
1
2 2
1 2
2 1
0
</p>