-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathDiagonalTraverse.java
More file actions
37 lines (36 loc) · 988 Bytes
/
DiagonalTraverse.java
File metadata and controls
37 lines (36 loc) · 988 Bytes
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
class DiagonalTraverse {
public int[] findDiagonalOrder(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int row = 0, col = 0;
int[] res = new int[m*n];
boolean dir = true; // UP - T, Down - F
for(int i = 0;i<m*n;i++) {
res[i] = mat[row][col];
if(dir) {
if(col == n-1) {
row++;
dir = false;
} else if(row == 0) {
col++;
dir = false;
} else {
row--;
col++;
}
} else {
if(row == m-1) {
col++;
dir = true;
} else if(col == 0) {
row++;
dir = true;
} else {
row++;
col--;
}
}
}
return res;
}
}