Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
Example 2:
Input: mat = [[1,2],[3,4]]
Output: [1,2,3,4]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
-105 <= mat[i][j] <= 105
Solutions
Solution 1: Fixed Point Traversal
Thinking
Traverse the matrix in zigzag diagonals. Simulating a direction and bouncing off edges needs many boundary cases. There are \(m+n-1\) diagonals, each with a closed-form start.
Diagonal \(k\) is collected top-right to bottom-left, starting at \((0,k)\) when \(k<n\) and \((k-n+1,n-1)\) otherwise. Even \(k\) is reversed to match the required zigzag.
Always walking down-left and flipping on even \(k\) avoids switching a direction vector on the border.
For each round \(k\), we fix the starting point from the top-right and traverse diagonally to the bottom-left to get \(t\). If \(k\) is even, we reverse \(t\).
The time complexity is \(O(m \times n)\), and the space complexity is \(O(1)\). Ignoring the space used for the answer.