Loading content...
You are given a two-dimensional grid of integers with m rows and n columns. Your task is to traverse all elements of the grid following a zigzag diagonal pattern.
Starting from the top-left corner at position (0, 0), you move along diagonals in an alternating fashion:
When you reach a boundary of the grid while traversing a diagonal, transition to the next diagonal and switch the direction of traversal.
Return a one-dimensional array containing all elements of the grid in the order they are visited during this zigzag diagonal walk.
Visual Representation: Imagine walking through the grid like the letter 'Z' repeated diagonally—moving up and to the right along one diagonal, then down and to the left along the next diagonal, and so on until all elements are covered.
mat = [[1,2,3],[4,5,6],[7,8,9]][1,2,4,7,5,3,6,8,9]Starting at (0,0)=1, move up-right to (0,1)=2. Hit top boundary, switch direction. Move down-left through (1,0)=4, (2,0)=7. Hit left boundary, switch direction. Move up-right through (1,1)=5, (0,2)=3. Hit top-right, switch direction. Move down-left to (1,2)=6. Continue to (2,1)=8, then (2,2)=9.
mat = [[1,2],[3,4]][1,2,3,4]Start at (0,0)=1, go up-right to (0,1)=2. Hit boundary, switch to down-left getting (1,0)=3. Switch again, move to (1,1)=4. All elements visited.
mat = [[1,2,3],[4,5,6]][1,2,4,5,3,6]For this 2×3 rectangular matrix: Start at 1, go up-right to 2. Switch to down-left getting 4, then up-right getting 5, 3. Finally down-left to 6.
Constraints