![]() |
VOOZH | about |
Given a 2D mat of size n*n, print the matrix in the following pattern.
Examples:
Input: n = 2, mat[][] = [[1, 2],
[3, 4]]
Output: [1, 2, 3, 4]
Explanation:
👁 ImageInput: n = 3, mat[][] = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Output: [1, 2, 4, 3, 5, 7, 6, 8, 9]
Explanation:
👁 Image
Table of Content
The idea is to use the value of i + j, since elements with the same value lie on the same diagonal. We create a temporary array of arrays and store same diagonal elements at one place using (i+j) as index. Finally iterate over the temporary array to print the items diagonally.
1 2 4 3 5 7 6 8 9
Traverse each diagonal directly by starting from every element in the first row and then from every element in the last column (Except the first element of the last column). From each starting point, move diagonally (down-left) and print elements until going out of bounds.
1 2 4 3 5 7 6 8 9