#K65287. Magic Matrix Transformation

    ID: 32164 Type: Default 1000ms 256MiB

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 and m describing the dimensions of the grid.
  • Then, n lines follow, each containing m 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.

## sample
1
2 2
1 2
2 1
0

</p>