Given a m * n matrix mat of integers, sort it diagonally in ascending order from the top-left to the bottom-right then return the sorted array.
Example 1:
Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
1 <= mat[i][j] <= 100
Solution:
class Solution {
public int[][] diagonalSort(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int k = m + n - 1;
for (int i = m - 1; i >= 0; i --) {
int[] arr = new int[Math.min(n, m - i)];
int x = i, y = 0, j = 0;
while (x < m && y < n) {
arr[j ++] = mat[x ++][y ++];
}
Arrays.sort(arr);
x = i;
y = 0;
j = 0;
while (x < m && y < n) {
mat[x ++][y ++] = arr[j ++];
}
}
for (int j = 1; j < n; j ++) {
int[] arr = new int[Math.min(m, n - j)];
int x = 0, y = j, i = 0;
while (x < m && y < n) {
arr[i ++] = mat[x ++][y ++];
}
Arrays.sort(arr);
x = 0;
y = j;
i = 0;
while (x < m && y < n) {
mat[x ++][y ++] = arr[i ++];
}
}
return mat;
}
}