Input: m = 3, n = 3
query[][] = [[1, 0, 1],
[3, 0, 0],
[3, 1, 0],
[2, 0, 1],
[3, 0, 0],
[3, 1, 0]]
Output: 4 1 5 2
Explanation: Initially the matrix is:
mat[][] = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
First Operation [1, 0, 1]: We need to swap row 0 and row 1.
After this operation, matrix becomes:
mat[][] =[[4, 5, 6],
[1, 2, 3],
[7, 8, 9]]
For the next two operation, we are required to print the elements at given cells.
Fourth Operation [2, 0, 1]: We need to swap column 0 and column 1.
After this operation matrix becomes:
mat[][] =[[5, 4, 6],
[2, 1, 3],
[8, 7, 9]]
For the next two operation, we are required to print the elements at given cells.
The idea is to create a matrix mat[][] of order m*n, initially filled with integers from 1 to m*n sequentially in a row-major order. For the queries of type 1 and 2, i.e. swap, traverse required row or column and swap the each of its elements. And for the query of type 3, i.e. print, we simply print the element at specified index.
The element at any position mat[x][y] in the matrix can be described as mat[x][y] = (n*x) + y + 1, where n is the count of columns. Instead of modifying the matrix directly, we can use two auxiliary arrays, rows[m] and cols[n]. The rows array is initialized with values from 0 to m-1, representing the indices of the rows, and the cols array is initialized with values from 0 to n-1, representing the indices of the columns.
To process a query of type 1, which swaps rows x and y, we simply swap the values of rows[x] and rows[y]. Similarly, for a query of type 2, which swaps columns x and y, we swap the values of cols[x] and cols[y]. For a query of type 3, which print the value at position (x, y), we calculate the position using the formula, mat[x][y] = rows[x]*n + cols[y] + 1.