|
| 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