All problems

Problem 493

Diagonal Traverse

Medium · 20 pts · Matrix, Simulation

Problem

Print all elements of an R x C matrix in zigzag diagonal order. The diagonals are the groups of cells (i, j) with the same i + j, taken in order of increasing i + j. The first diagonal is read upwards (from bottom-left to top-right), the next downwards (from top-right to bottom-left), and the direction keeps alternating.

Input

First line: R and C. Next R lines: C integers each.

Output

Print the R · C elements in diagonal order, separated by spaces.

Constraints

1 <= R, C <= 300; -100000 <= value <= 100000

Example input

3 3
1 2 3
4 5 6
7 8 9

Example output

1 2 4 7 5 3 6 8 9

Explanation

For 1 2 3 / 4 5 6 / 7 8 9 the diagonals are [1], [2 4], [3 5 7], [6 8], [9]. Reading them alternately upwards and downwards gives 1 2 4 7 5 3 6 8 9.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Spiral Matrix II Next: Reshape the Matrix