[Leetcode] Problem 498 - Diagonal Traverse

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:

wmY5uR.png

Note

The total number of elements of the given matrix will not exceed 10,000.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public int[] findDiagonalOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return new int[0];

int m = matrix.length;
int n = matrix[0].length;
int[] result = new int[m * n];
int row = 0;
int col = 0;
int dir = 1;

for (int i = 0; i < m * n; i++) {
result[i] = matrix[row][col];
row -= dir;
col += dir;

if (row >= m) {
row = m - 1;
col += 2;
dir = -dir;
}

if (col >= n) {
col = n - 1;
row += 2;
dir = -dir;
}

if (row < 0) {
row = 0;
dir = -dir;
}

if (col < 0) {
col = 0;
dir = -dir;
}
}

return result;
}