×

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

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Frugal number in Java

A frugal number is a positive integer with base b that has more digits than the number of prime factors it can be factored into (including exponents greater than 1)....

3 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

How to achieve Multiple Inheritance in Java

Multiple Inheritance is the type of inheritance where one class inherits the properties of more than one super class. For example, class Child inherits (extends) the classes Father and Mother....

4 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.