Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e40eddf

Browse files
Create 3446.py
1 parent 05c7070 commit e40eddf

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

‎3001-3500/3446.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution:
2+
def sortMatrix(self, matrix):
3+
# Dictionary to store diagonals, where key is the difference of row and column index
4+
diagonal_map = {}
5+
rows, cols = len(matrix), len(matrix[0])
6+
7+
# Traverse the matrix and group elements by their diagonal (row - col)
8+
for i in range(rows):
9+
for j in range(cols):
10+
key = i - j
11+
if key not in diagonal_map:
12+
diagonal_map[key] = []
13+
diagonal_map[key].append(matrix[i][j])
14+
15+
# Sort each diagonal: negative keys (upper diagonals) in ascending order,
16+
# positive keys (lower diagonals) in descending order
17+
for key in diagonal_map:
18+
if key < 0:
19+
diagonal_map[key].sort()
20+
else:
21+
diagonal_map[key].sort(reverse=True)
22+
23+
# Populate the sorted values back into the matrix
24+
for i in range(rows):
25+
for j in range(cols):
26+
key = i - j
27+
matrix[i][j] = diagonal_map[key].pop(0)
28+
29+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /