3446. Sort Matrix by Diagonals #2106
-
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to sort the diagonals of a square matrix in two different ways based on their position relative to the main diagonal. The diagonals in the bottom-left triangle (including the main diagonal) should be sorted in non-increasing order, while the diagonals in the top-right triangle should be sorted in non-decreasing order. Approach
Let's implement this solution in PHP: 3446. Sort Matrix by Diagonals <?php
/**
* @param Integer[][] $grid
* @return Integer[][]
*/
function sortMatrix($grid) {
$n = count($grid);
$groups = [];
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++) {
$d = $i - $j;
if (!isset($groups[$d])) {
$groups[$d] = [];
}
$groups[$d][] = $grid[$i][$j];
}
}
foreach ($groups as $d => $list) {
if ($d >= 0) {
rsort($list);
} else {
sort($list);
}
$groups[$d] = $list;
}
$result = array_fill(0, $n, array_fill(0, $n, 0));
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++) {
$d = $i - $j;
$result[$i][$j] = array_shift($groups[$d]);
}
}
return $result;
}
// Test cases
$grid1 = [[1,7,3],[9,8,2],[4,5,6]];
print_r(sortMatrix($grid1));
// Expected: [[8,2,3],[9,6,7],[4,5,1]]
$grid2 = [[0,1],[1,2]];
print_r(sortMatrix($grid2));
// Expected: [[2,1],[1,0]]
$grid3 = [[1]];
print_r(sortMatrix($grid3));
// Expected: [[1]]
?> Explanation:
This approach efficiently groups, sorts, and reassembles the matrix diagonals, meeting the problem's requirements with clarity and simplicity. The complexity is manageable given the constraints, making it a practical solution. |
Beta Was this translation helpful? Give feedback.
We need to sort the diagonals of a square matrix in two different ways based on their position relative to the main diagonal. The diagonals in the bottom-left triangle (including the main diagonal) should be sorted in non-increasing order, while the diagonals in the top-right triangle should be sorted in non-decreasing order.
Approach
d = i - j
, wherei
is the row index andj
is the column index. Diagonals withd >= 0
belong to the bottom-left triangle, and those withd < 0
belong to the top-right triangle.d >= 0
, sort the elements in non-increasing o…