Diverse Game

Diverse Game
Codeforces easy

There are \(T\) test cases. In each test you are given a matrix \(A\) of size \(N \times M\), containing all integers from \(1\) to \(N \cdot M\) exactly once. Construct a matrix \(B\) of the same size such that for every cell \((i, j)\), \(A_{i,j} \neq B_{i,j}\). If it is impossible, output \(-1\).

Solution

First, to loop over all \(T\) tests we are going to write this.

int test_cases;
cin >> test_cases;

while(testcases--){
    // solution for each testcase is written here
}

The only case with no solution is when \(N = M = 1\). Otherwise, let \(B_{i,j} = A_{i,j} + 1\), and if \(A_{i,j} = N \cdot M\), set \(B_{i,j} = 1\). This ensures \(B_{i,j} \neq A_{i,j}\) for all cells.

int n, m;
cin >> n >> m;

int a[n][m], b[n][m];

for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        cin >> a[i][j];

        if (a[i][j] == n * m) b[i][j] = 1;
        else b[i][j] = a[i][j] + 1;
    }
}

Lastly, we need to check if \(N = M = 1\). Otherwise print matrix \(B\).

if (n == 1 && m == 1) {
    cout << -1 << "\n";
    continue; // to go to the next testcase
}
// now it's guaranteed that n = m = 1 doesn't apply
for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        cout << b[i][j] << ' ';
    }
    cout << endl;// ensures that each row is printed in a seperate line
}