Diagonal Traverse
Given an m x n matrix mat, return all its elements in diagonal order. Traversal starts at the top-left cell and walks the anti-diagonals (cells where row + col is constant), reversing direction on each successive diagonal: the first diagonal goes up-right, the next goes down-left, and so on.
Open official problem prompt ↗Flatten a 2D grid into a 1D list where elements come out along anti-diagonals, with the walk direction flipping on each diagonal so the reading path is continuous.
Think of a boustrophedon plow: the farmer plows one furrow up the field, then turns and plows the next furrow back down, alternating direction each pass so no time is wasted returning to the start.
- Input
- mat = [[1,2,3],[4,5,6],[7,8,9]]
- Output
- [1,2,4,7,5,3,6,8,9]
- Why
- Diagonal 0 = [1] (up), diagonal 1 = [2,4] (down), diagonal 2 = [7,5,3] (up), diagonal 3 = [6,8] (down), diagonal 4 = [9], concatenated in that order.
m == mat.lengthn == mat[i].length1 <= m, n <= 10^41 <= m * n <= 10^4-10^5 <= mat[i][j] <= 10^5