forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiagonal Traverse.java
More file actions
51 lines (47 loc) · 1.41 KB
/
Diagonal Traverse.java
File metadata and controls
51 lines (47 loc) · 1.41 KB
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
class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) {
return new int[]{};
}
int dir = 0;
int x = 0;
int y = 0;
int numOfRows = matrix.length;
int numOfCols = matrix[0].length;
int[] ans = new int[matrix.length * matrix[0].length];
for (int i = 0; i < numOfRows * numOfCols; i++) {
ans[i] = matrix[x][y];
if ((x + y) % 2 == 0) {
// If last column then go to next row
if (y == numOfCols - 1) {
x++;
}
// If first row but not last column then go to next column
else if (x == 0) {
y++;
}
// Go up
else {
x--;
y++;
}
}
else {
// If last row then go to next column
if (x == numOfRows - 1) {
y++;
}
// If first column but not last row then go to next row
else if (y == 0) {
x++;
}
// Go down
else {
x++;
y--;
}
}
}
return ans;
}
}