498. Diagonal Traverse

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Solution {
private static final int[][] DIRECTIONS = new int[][]{{-1, 1}, {1, -1}};

public int[] findDiagonalOrder(int[][] mat) {
int m = mat.length, n = mat[0].length;

int[] ans = new int[m * n];
int index = 0;

int directionIndex = 0;
int i = 0, j = 0;
while (index < ans.length) {
ans[index++] = mat[i][j];
i += DIRECTIONS[directionIndex][0];
j += DIRECTIONS[directionIndex][1];

if (i < 0 && j == n) {
// 右上角
i = 1;
j = n - 1;
directionIndex = 1 - directionIndex;
continue;
}
if (j < 0 && i == m) {
// 左下角
i = m - 1;
j = 1;
directionIndex = 1 - directionIndex;
continue;
}

if (i < 0) {
i = 0;
directionIndex = 1 - directionIndex;
continue;
}
if (i == m) {
i = m - 1;
j += 2;
directionIndex = 1 - directionIndex;
continue;
}
if (j < 0) {
j = 0;
directionIndex = 1 - directionIndex;
continue;
}
if (j == n) {
j = n - 1;
i += 2;
directionIndex = 1 - directionIndex;
continue;
}
}

return ans;
}
}

References

498. Diagonal Traverse