830. Fill a matrix along zigzag diagonals
Image codecs such as JPEG read an 8 by 8 block of coefficients in a zigzag order along anti-diagonals so that low frequencies come first. This exercise builds that order.
Write zigzag_fill(rows, cols). Return a rows by cols matrix (a list of lists) filled with 1, 2, 3, ... in zigzag order. Start at the top-left cell. Walk anti-diagonal 0, then 1, then 2, and so on, where anti-diagonal d holds cells with row + col == d. On even d move up and to the right (row decreasing); on odd d move down and to the left (row increasing).
def zigzag_fill(rows, cols)Example 1
Input: zigzag_fill(3, 3)
Output: [[1, 2, 6], [3, 5, 7], [4, 8, 9]]
Example 2
Input: zigzag_fill(1, 4)
Output: [[1, 2, 3, 4]]
Constraints
- 1 <= rows, cols <= 500
Hint 1
Name the diagonal by row + col.
Hint 2
Clamp the row range per diagonal.
Hint 3
Flip direction by parity of d.
Common mistakes
- Simulating moves and bouncing off edges with many special cases.
- Getting the parity backwards so the second cell is below the first.
- Assuming the matrix is square.
Understand the idea
Index arithmetic on anti-diagonals replaces a fiddly direction-switching walk. In a 3 by 3 grid, diagonal 2 holds (2, 0), (1, 1), (0, 2); because 2 is even it is walked from row 2 up to row 0, so those cells get 4, 5, 6. The approach is O(rows x cols) and handles any rectangle.