×

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern.

Print Matrix Diagonally in Java

Input : mat[3][3] = {{1, 2, 3},

                     {4, 5, 6},

                     {7, 8, 9}}

Output : 1 2 4 7 5 3 6 8 9.

Explanation: Starting from the number 1

then diagonally from above to below that is 2 and 4

then diagonally upward from below that is 7, 5, 3

then diagonally from top to bottom that is  6, 8

Next, go up till you reach the end 9.

Input :  mat[4][4] =  {{1,  2,  3,  10},

                      {4,  5,  6,  11},

                      {7,  8,  9,  12},

                      {13, 14, 15, 16}}

Output:  1 2 4 7 5 3 10 6 8 13 14 9 11 12 15 16

Explanation: Starting from the number 1

then diagonally from above to below that is 2 and 4

then diagonally upward from below that is 7, 5, 3

then diagonally from above to below that is 10 6 8 13

T then diagonally from lower to higher that is 14 9 11

then diagonally from above to below that is 12 15

then it will end at the number 16

reach: As can be seen from the diagram, each piece is written either diagonally or upwards diagonally downward. Print the items diagonally upward starting at index (0,0), then change the orientation, change the column, and print them diagonally downward. Up until the final component is reached, this cycle is repeated.

Algorithm for the approach:

  1. Create the variables i=0 and j=0 to hold the current row and column indices.
  2. Continually loop between 0 and n*n, in which n is a matrix side.
  3. To determine if the orientation is above or downwards, use the flag isUp. The orientation is originally upward when isUp = true.
  4. Start printing elements if isUp = 1 by increasing the column index and decreasing the row index.
  5. The column index will be decreased and the row index will be increased if isUp = 0.
  6. Go to the following row or column (next beginning row and column).
  7. Repeat until all elements have been explored.

PrintMatrixInDiagonal.java

// Matrix printing in diagonal order using a Java program
class PrintMatrixInDiagonal  {
    static final int MAX = 100;
    static void printMatrixInDiagonal(int mat[][], int m)
    {
        // Set the following element's indexes to their initial values.
        int s = 0, h = 0;
        // the starting direction is up from down.
        boolean isUpwa = true;
        // until each entry in the matrix has been traversed
        for (int l = 0; l < m * m;) {
           // Traverse from downhill 
         // to upward if isUpwa = true.
            if (isUpwa) {
                for (; s >= 0 && h < m; h++, s--) {
                    System.out.print(mat[i][j] + " ");
                    l++;
                }
                // According to the direction, align s and h.
                if (s < 0 && h <= m - 1)
                    s = 0;
                if (h == m) {
                    s = s + 2;
                    h--;
                }
            }
            // Traverse from up to down if isUpwa = 0.
            else {
                for (; h >= 0 && s < m; s++, h--) {
                    System.out.print(mat[s][h] + " ");
                    l++;
                }
                // According to the direction, align s and h.
                if (h < 0 && s <= m - 1)
                    h = 0;
                if (s == m) {
                    h = h + 2;
                    s--;
                }
            }
            // To alter the direction, revert the isUpwa
            isUpwa = !isUpwa;
        }
    }
    // It is the Driver code
    public static void main(String[] args)
    {
        int mat[][] = { { 1, 2, 3 },
                        { 4, 5, 6 },
                        { 7, 8, 9 } };
        int n = 3;
        printMatrixDiagonal(mat, m);
    }
}

Output:

1  2  4  7  5  3  6  8  9

Alternative Version:

The same strategy as described before is used in this straightforward and condensed implementation.

// Matrix printing in diagonal order using a Java program
public class PrintMatrixInDiagonal {
    public static void main(String[] args)
    {
        // Initializing the matrix
        int[][] mat = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 } };
        // size is taken as m
        // When the iterator count reaches m, 
       // it rises until the mode is switched to derive up
       //down traversal, at which point it reduces.
        int m = 4, type = 0, iti = 0, lower = 0;
 
        // There will be 2m iterations.
        for (int p = 0; p < (2 * m - 1); p++) {
            int p1 = p;
            if (p1 >= m) {
                type++;
                p1 = m - 1;
                iti--;
                lower++;
            }
            else {
                lower = 0;
                iti++;
            }
            for (int s = p1; s >= lower; s--) {
                if ((p1 + type) % 2 == 0) {
                    System.out.println(mat[s][p1 + lower - s]);
                }
                else {
                    System.out.println(mat[p1 + lower - s][s]);
                }
            }
        }
    }
}

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Related Topics

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

How to Convert String to char in Java

How to Convert String to char in Java There are two methods to convert String to char are: Using charAt() method Using tocharArray() method Using charAt() method This is the method of String class that...

3 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.