Search code examples
javamatrixdiagonal

Reverse diagonal traversal of a matrix (start from top right side)



I have a code from another site, which gives me the Zigzag (or diagonal) traversal of Matrix.

Given array in the code:

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

For the given array in the code, the output is:

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

So it starts from the top left side. (From 1)

I want to make it start from the top right side, so the first element is "4", the second element is "8 3", third is "12 7 2", fourth is "16 11 6 1" etc... But I can't make it. Could you help me rewriting the code for me?

class GFG {
    static final int ROW = 5;
    static final int COL = 4;
 
    static int min(int a, int b)
    {
        return (a < b) ? a : b;
    }
 
    static int min(int a, int b, int c)
    {
        return min(min(a, b), c);
    }
 
    static int max(int a, int b)
    {
         return (a > b) ? a : b;
    }
 
    static void diagonalOrder(int matrix[][])
    {

        for (int line = 1; line <= (ROW + COL - 1); line++) {
 
            int start_col = max(0, line - ROW);
 
            int count = min(line, (COL - start_col), ROW);
 
            for (int j = 0; j < count; j++)
                System.out.print(matrix[min(ROW, line)- j- 1][start_col + j]+ " ");
 
            System.out.println();
        }
    }
 
    public static void main(String[] args)
    {
        int M[][] = {
            { 1, 2, 3, 4 },
            { 5, 6, 7, 8 },
            { 9, 10, 11, 12 },
            { 13, 14, 15, 16 },
            { 17, 18, 19, 20 },
        };
 
        System.out.print(
            "\nDiagonal printing of matrix is \n");
        diagonalOrder(M);
    }
}

I tried to make it but it didn't work properly.


Solution

  • Flipping the matrix horizontally worked for me, thanks for the answers.

    flipping a multi-dimensional array java