easy +12 pts

Diagonal Traverse Matrix

Return all elements of a 2D matrix in diagonal zigzag order.

Write a function `diagonal_traverse(matrix)` that accepts a 2D list of integers `matrix` and returns a flat list of all elements in the order traversed diagonally with alternating direction per diagonal. The traversal starts at the top-left cell (0,0) and proceeds diagonally up-right first, then down-left, alternating with each subsequent diagonal, covering every cell exactly once. The matrix may be empty or have dimensions up to 100x100. You must return the list in the correct order.

Constraints

0 <= rows, cols <= 100. Elements are integers. The input matrix is rectangular (all rows have same length). Total elements up to 10,000.

Example

>>> diagonal_traverse([[1,2,3],[4,5,6],[7,8,9]])
[1,2,4,7,5,3,6,8,9]

>>> diagonal_traverse([[1,2],[3,4]])
[1,2,3,4]
12 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

For each diagonal, the sum of indices i+j is constant.
Handle alternating direction by checking if (i+j) is even (up-right) or odd (down-left).
When moving up-right, the starting cell is either on the first column or last row; use reversed order to collect elements.
When moving down-left, start from either the first row or last column.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.