Print Matrix Diagonally in Java
In this section, we will understand how to print a matrix in a diagonal order. Also, create a Java program that prints the matrix in a diagonal order.
First, we will understand the diagonal printing order. Consider the following matrix having 4 rows and 5 columns.
The diagonal pattern will be:
From the above pattern, we observe that the diagonal 10 11 12 13 prints twice because 10 is the first element of the fifth row and the last element of the first column. It is common in both.
Therefore, we can calculate the formula for the number of diagonals in a matrix, as m+n-1 (where m is the number of rows and n is the number of columns. -1 denotes a diagonal that is counted twice.).
Let's see the flow.
Consider a matrix. In the following matrix, the first digit denotes the row number and the second digit denotes the column number.
Suppose, we have to print the diagonal elements of 20 11 02 (where 20 is the first element, 11 is the second element, and 02 is the third and last element of the diagonal).
We observe that each time when we find the next diagonal element i is decremented by 1 and j is incremented by 1. Hence,
Therefore, if we know the first element of the diagonal, we can find all the diagonal elements up to the end by using the above logic.
Let's implement the above logic in a Java program.
Matrix elements in diagonal form are: 3 2 7 8 1 9 6 5 4
Similarly, we can also print a matrix with any number of rows and columns.