### 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 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