Problem 570
Sort the Matrix Diagonally
Medium · 20 pts · Matrix, Sorting
Problem
A matrix diagonal is a line of cells that starts in the top row or the leftmost column and goes down and to the right until it leaves the matrix. Sort the values on every such diagonal in increasing order (from top-left to bottom-right) and print the resulting matrix. All cells on one diagonal share the same value of row - column, so group the cells by that key, sort each group, and write them back.
Input
The first line contains R and C. Each of the next R lines contains C integers.
Output
Print the matrix after sorting every diagonal, one row per line.
Constraints
1 <= R, C <= 100; 1 <= values <= 100
Example input
3 4 3 3 1 1 2 2 1 2 1 1 1 2
Example output
1 1 1 1 1 2 2 2 1 2 3 3
Explanation
In the matrix 3 3 1 1 / 2 2 1 2 / 1 1 1 2, the main diagonal holds 3, 2, 1, which sorted becomes 1, 2, 3. After sorting every diagonal the matrix is 1 1 1 1 / 1 2 2 2 / 1 2 3 3.