Diagonal Traverse Java Solution - The Coding Shala

Home >> Interview Questions >> Diagonal Traverse

Diagonal Traverse

Problem: 
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.

Example:
Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

Output:  [1,2,4,7,5,3,6,8,9]

Explanation:
Diagonal Traverse - The Coding Shala

Diagonal Traverse Java Solution

Approach: 

Traverse the Matrix.

Java Code:: 

class Solution {
    public int[] findDiagonalOrder(int[][] matrix) {
        int row = matrix.length;
        if(row == 0) return (new int[0]); //if empty matrix
        int col = matrix[0].length;
        int[] ans = new int[row*col];
        int index = 0;
        int i =0, j=0;
        
        while(i<row && j<col){
            
            while(i>=0 && j<col){ //moving up
                ans[index] = matrix[i][j];
                index++;
                j++;
                i--;
            }
            i++;
            if(j==col){ //reach beyond column
                i++;
                j--;
            }
            while(j>=0 && i<row){ //moving down
                ans[index] = matrix[i][j];
                index++;
                i++;
                j--;
            }
            j++;
            if(i==row){ //reach beyond row
                i--;
                j++;
            }
           // for(int tmp = 0; tmp<index;tmp++) System.out.print(ans[tmp]+" ");
        }
        return ans;
    }
}



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala