forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort_matrix_diagonally.py
77 lines (66 loc) · 1.81 KB
/
sort_matrix_diagonally.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
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.
mat = [
[3,3,1,1],
[2,2,1,2],
[1,1,1,2]
]
Should return:
[
[1,1,1,1],
[1,2,2,2],
[1,2,3,3]
]
"""
from heapq import heappush, heappop
from typing import List
def sort_diagonally(mat: List[List[int]]) -> List[List[int]]:
# If the input is a vector, return the vector
if len(mat) == 1 or len(mat[0]) == 1:
return mat
# Rows + columns - 1
# The -1 helps you to not repeat a column
for i in range(len(mat)+len(mat[0])-1):
# Process the rows
if i+1 < len(mat):
# Initialize heap, set row and column
h = []
row = len(mat)-(i+1)
col = 0
# Traverse diagonally, and add the values to the heap
while row < len(mat):
heappush(h, (mat[row][col]))
row += 1
col += 1
# Sort the diagonal
row = len(mat)-(i+1)
col = 0
while h:
ele = heappop(h)
mat[row][col] = ele
row += 1
col += 1
else:
# Process the columns
# Initialize heap, row and column
h = []
row = 0
col = i - (len(mat)-1)
# Traverse Diagonally
while col < len(mat[0]) and row < len(mat):
heappush(h, (mat[row][col]))
row += 1
col += 1
# Sort the diagonal
row = 0
col = i - (len(mat)-1)
while h:
ele = heappop(h)
mat[row][col] = ele
row += 1
col += 1
# Return the updated matrix
return mat