-
Notifications
You must be signed in to change notification settings - Fork 354
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 1329_Sort_the_Matrix_Diagonally_(Medium).py
Turn matrix on 45 degrees, sort and then turn back
- Loading branch information
1 parent
cfcf396
commit 514c806
Showing
1 changed file
with
24 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
class Solution: | ||
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: | ||
if not mat: return [[]] | ||
m = len(mat) | ||
n = len(mat[0]) | ||
dlen = m + n - 1 | ||
diff = n - m | ||
diagonals = [] | ||
for i in range(dlen): | ||
diagonals.append([]) | ||
for i in range(m): | ||
for j in range(n): | ||
diagonals[diff + i-j].append(mat[i][j]) | ||
|
||
for i in range(dlen): | ||
diagonals[i] = sorted(diagonals[i]) | ||
|
||
for i in range(m): | ||
for j in range(n): | ||
i_d = diff + i - j | ||
j_d = min(j, i) | ||
mat[i][j] = diagonals[i_d][j_d] | ||
|
||
return mat |