498. Diagonal Traverse #2094
-
Topics: Given an Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to traverse a given matrix in a diagonal order, alternating the direction of traversal for each diagonal. The key observation is that the sum of the indices (i + j) for each element in a diagonal is constant. For even-indexed diagonals (by sum), we traverse from the bottom to the top, and for odd-indexed diagonals, we traverse from the top to the bottom. Approach
Let's implement this solution in PHP: 498. Diagonal Traverse <?php
/**
* @param Integer[][] $mat
* @return Integer[]
*/
function findDiagonalOrder($mat) {
$m = count($mat);
$n = count($mat[0]);
$result = [];
$maxSum = $m + $n - 2;
for ($s = 0; $s <= $maxSum; $s++) {
if ($s % 2 == 0) {
$i = min($s, $m - 1);
$j = $s - $i;
while ($i >= 0 && $j < $n) {
$result[] = $mat[$i][$j];
$i--;
$j++;
}
} else {
$j = min($s, $n - 1);
$i = $s - $j;
while ($i < $m && $j >= 0) {
$result[] = $mat[$i][$j];
$i++;
$j--;
}
}
}
return $result;
}
// Test cases
// Example 1:
$mat1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
print_r(findDiagonalOrder($mat1));
// Expected: [1,2,4,7,5,3,6,8,9]
// Example 2:
$mat2 = [
[1, 2],
[3, 4]
];
print_r(findDiagonalOrder($mat2));
// Expected: [1,2,3,4]
?> Explanation:
This approach efficiently collects all elements in the required diagonal order by leveraging the constant sum of indices for each diagonal and alternating traversal directions. The solution handles all edge cases, including non-square matrices, seamlessly. |
Beta Was this translation helpful? Give feedback.
We need to traverse a given matrix in a diagonal order, alternating the direction of traversal for each diagonal. The key observation is that the sum of the indices (i + j) for each element in a diagonal is constant. For even-indexed diagonals (by sum), we traverse from the bottom to the top, and for odd-indexed diagonals, we traverse from the top to the bottom.
Approach
s
(from 0 tom + n - 2
), ifs
is even, we start from the bottom-mos…