498_Diagonal Traverse
Last updated
Last updated
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Idea:
Have a flag to show if the direction goes up right or down left, take different operation for different direction, update the flag when approach the border.
Take special care of elements on the border of the matrix, and the update rules are different for the four borders.
Idea:
In each diagonal, col index + row index is a constant. We are sorting this constant in ascending order.
In a diagonal, the direction which loops each element is decided by if col index + row index is odd or even. If it's even, it traverse larger rows, smaller cols first. If it's odd, it traverse larger cols, small rows first.
Time Complexity:
Space Complexity:
Time Complexity:
Space Complexity: