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:

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

img

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

解法1:

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
class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
return new int[0];
}
int m = matrix.length;
int n = matrix[0].length;
int[] res = new int[m * n];
int[][] dirs = new int[][]{{-1,1},{1,-1}};
int d = 0;
int row = 0, col = 0;
for (int i = 0; i < m * n; i++) {
res[i] = matrix[row][col];
row += dirs[d][0];
col += dirs[d][1];
if (row >= m) {
row = m - 1;
col += 2;
d = 1 - d;
}
if (col >= n) {
col = n - 1;
row += 2;
d = 1 - d;
}
if (row < 0) {
row = 0;
d = 1 - d;
}
if (col < 0) {
col = 0;
d = 1 - d;
}
}
return res;
}
}