#C8275. Grid Transformation to Sorted Order
Grid Transformation to Sorted Order
Grid Transformation to Sorted Order
You are given an n×m grid of integers. Your task is to rearrange the grid so that every row and every column is sorted in non-decreasing order.
You are allowed to rearrange all the numbers arbitrarily (i.e. you can extract all numbers, sort them, and then fill the grid in row‐major order). If it is possible to achieve this, output YES
followed by the rearranged grid; otherwise, output NO
.
Formally, let \(a_{i,j}\) be the number in the \(i\)th row and \(j\)th column. After transformation, the grid \(b\) must satisfy:
\[ b_{i,1} \le b_{i,2} \le \cdots \le b_{i,m} \quad\text{for every }1\le i\le n, \]
and
\[ b_{1,j} \le b_{2,j} \le \cdots \le b_{n,j} \quad\text{for every }1\le j\le m. \]
You may assume that rearranging all numbers always produces a valid solution. Note that although in some variants the answer may be NO
, in this problem the intended solution is to output the sorted grid.
Input/Output Instructions: Read from standard input and write to standard output.
inputFormat
The first line contains two integers n
and m
(1 ≤ n, m ≤ 1000) — the number of rows and columns of the grid.
The next n
lines each contain m
integers. The \(j\)th integer in the \(i\)th line represents the element \(a_{i,j}\) in the grid.
You can assume that all numbers fit in a 32-bit signed integer.
outputFormat
If it is possible to transform the grid, print YES
on the first line. Then print n
lines, each containing m
integers — the transformed grid, where each row and each column is sorted in non-decreasing order.
If it is impossible, print only NO
.
2 2
3 1
4 2
YES
1 2
3 4