#C11222. Transforming a Grid into a Latin Square
Transforming a Grid into a Latin Square
Transforming a Grid into a Latin Square
You are given an n × n grid in which each row is a permutation of the integers from 1 to n. Your task is to transform the grid into a Latin square by performing a sequence of operations. In a Latin square, every row and every column contains each integer from 1 to n exactly once.
You are allowed to perform the following operations:
row x y
: Swap row x with row y (1-indexed).column x y
: Swap column x with column y (1-indexed).
The objective is to use as few operations as possible. Note that if the grid is already a Latin square, you should output 0 operations. Also, note that it is only possible to transform the grid into a Latin square if each row and each column (when viewed as a multiset) is exactly equal to {1, 2, …, n}.
Warning: The input is provided such that it is always possible to get a Latin square through row and column swaps.
inputFormat
The first line contains an integer n (1 ≤ n ≤ 50) — the size of the grid. The following n lines each contain n integers separated by spaces, representing the grid. It is guaranteed that each row is a permutation of the integers from 1 to n, and the grid is transformable into a Latin square by row and column swaps.
outputFormat
On the first line, print an integer q (0 ≤ q ≤ 1000) representing the number of operations performed. Then print q lines, each describing one operation in one of the following forms:
row x y
— indicating a swap of row x with row y.column x y
— indicating a swap of column x with column y.
If the grid is already a Latin square, your program should output 0 and nothing more.
## sample4
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
0
</p>