topic:
A matrix diagonal is a diagonal line starting from an element in the topmost row or leftmost column of the matrix and going down the right direction to an element at the end of the matrix. For example, a matrix mat
has 6
rows and columns 3
, and the matrix diagonalmat[2][0]
from the start will go through , , and .mat[2][0]
mat[3][1]
mat[4][2]
Given a m * n
matrix of integers mat
, please sort the elements on the diagonal of the same matrix in ascending order and return the sorted matrix.
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]]
Example 2:
Input: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22, 27,33,25,68,4],[84,28,14,11,5,50]] output: [[5,17,4,1,52,7],[11,11,25,45 ,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]
hint:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
1 <= mat[i][j] <= 100
code:
class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
m = len(mat)
n = len(mat[0])
for i in range(m):
list_sort = []
ii = i
jj = 0
while True:
list_sort.append(mat[ii][jj])
ii = ii + 1
jj = jj + 1
if ii > m-1 or jj > n-1:
break
list_sort.sort(reverse=True)
for s_i in range(len(list_sort)):
ii = ii - 1
jj = jj - 1
mat[ii][jj] = list_sort[s_i]
for j in range(n):
list_sort = []
ii = 0
jj = j
while True:
list_sort.append(mat[ii][jj])
ii = ii + 1
jj = jj + 1
if ii > m-1 or jj > n-1:
break
list_sort.sort(reverse=True)
for s_i in range(len(list_sort)):
ii = ii - 1
jj = jj - 1
mat[ii][jj] = list_sort[s_i]
return mat
result: