2
* Simulate Diagonal Order Traversal4
* <p>r+c determines which diagonal you are on. For ex: [2,0],[1,1],[0,2] are all on same diagonal5
* with r+c =2. If you check the directions of diagonals, first diagonal is up, second diagonal is6
* down, third one is up and so on.. Therefore (r+c)%2 simply determines direction. Even is UP7
* direction. Odd is DOWN direction.9
* <p>Time Complexity: O(M*N)11
* <p>Space Complexity: O(1) without considering result space.13
* <p>M = Number of rows. N = Number of columns.16
public int[] findDiagonalOrder(int[][] matrix) {18
throw new IllegalArgumentException("Input matrix is null");20
if (matrix.length == 0 || matrix[0].length == 0) {24
int rows = matrix.length;25
int cols = matrix[0].length;26
int[] result = new int[rows * cols];30
for (int i = 0; i < result.length; i++) {31
result[i] = matrix[r][c];32
if ((r + c) % 2 == 0) { // Move Up34
// Reached last column. Now move to below cell in the same column.35
// This condition needs to be checked first due to top right corner cell.38
// Reached first row. Now move to next cell in the same row.41
// Somewhere in middle. Keep going up diagonally.47
// Reached last row. Now move to next cell in same row.48
// This condition needs to be checked first due to bottom left corner cell.51
// Reached first columns. Now move to below cell in the same column.54
// Somewhere in middle. Keep going down diagonally.