#K35517. Diagonal Traversal of Matrix
Diagonal Traversal of Matrix
Diagonal Traversal of Matrix
You are given a matrix of size \(M \times N\). Your task is to print the elements of the matrix in a specific diagonal order. The diagonals are obtained by the following process:
- For each row index \(0 \leq i < M\), start a diagonal from the element at \( (i, 0) \).
- Then, for each column index \(1 \leq j < N\), start a diagonal from the element at \( (M-1, j) \).
For each diagonal, move upward and to the right (i.e. decrement the row index and increment the column index) and collect all elements until you go out-of-bound of the matrix. Print each diagonal on a new line with the elements separated by a single space.
Note: \(M\) and \(N\) are positive integers representing the number of rows and columns respectively.
inputFormat
The first line contains two integers \(M\) and \(N\) representing the number of rows and columns respectively.
The next \(M\) lines each contain \(N\) integers separated by spaces, representing the rows of the matrix.
outputFormat
Output the diagonals of the matrix in the specified order. Each line of the output should contain the elements of one diagonal separated by a single space.
## sample4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
1
5 2
9 6 3
13 10 7 4
14 11 8
15 12
16
</p>