Sort the Matrix Diagonally
Description
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(javascript)
/**
* @param {number[][]} mat
* @return {number[][]}
*/
const diagonalSort = function (mat) {
const sort = (row, column) => {
for (let i = row, j = column; i < mat.length && j < mat[i].length; i++, j++) {
for (let m = i + 1, n = j + 1; m < mat.length && n < mat[m].length; m++, n++) {
if (mat[i][j] > mat[m][n]) {
const temp = mat[i][j]
mat[i][j] = mat[m][n]
mat[m][n] = temp
}
}
}
}
for (let j = 0; j < mat[0].length; j++) {
sort(0, j)
}
for (let i = 1; i < mat.length; i++) {
sort(i, 0)
}
return mat
}