@@ -10,41 +10,48 @@ public static class Solutoin1 {
10
10
/**
11
11
* Reference: https://discuss.leetcode.com/topic/77865/concise-java-solution/2
12
12
* Just keep walking the matrix, when hitting the four borders (top, bottom, left or right),
13
- * just directions and keep walking.
13
+ * change directions and keep walking:
14
+ * <p>
15
+ * if out of bottom border (i >= m), then i = m - 1, j += 2, change walk direction;
16
+ * if out of top border (i < 0), then i = 0, change walk direction;
17
+ * if out of left border (j < 0), then j = 0, change walk direction;
18
+ * if out of right border (j >= n), then j = n - 1, i += 2, change walk direction.
14
19
*/
15
- public int [] findDiagonalOrder (int [][] matrix ) {
16
-
17
- if (matrix == null || matrix .length == 0 ) {
20
+ public int [] findDiagonalOrder (int [][] mat ) {
21
+ if (mat == null || mat .length == 0 ) {
18
22
return new int [0 ];
19
23
}
20
- int m = matrix .length ;
21
- int n = matrix [0 ].length ;
24
+ int m = mat .length ;
25
+ int n = mat [0 ].length ;
22
26
int [] result = new int [m * n ];
23
- int d = 1 ;
27
+ //{-1,1} goes from top left to bottom right
28
+ //{1,-1} goes from top right to bottom left
29
+ int [][] dirs = new int [][]{{-1 , 1 }, {1 , -1 }};
24
30
int i = 0 ;
25
31
int j = 0 ;
32
+ int d = 0 ;
26
33
for (int k = 0 ; k < m * n ; ) {
27
- result [k ++] = matrix [i ][j ];
28
- i -= d ;
29
- j += d ;
34
+ result [k ++] = mat [i ][j ];
35
+ i += dirs [ d ][ 0 ] ;
36
+ j += dirs [ d ][ 1 ] ;
30
37
31
38
if (i >= m ) {
32
39
i = m - 1 ;
33
40
j += 2 ;
34
- d = - d ;
41
+ d = 1 - d ;
35
42
}
36
43
if (j >= n ) {
37
44
j = n - 1 ;
38
45
i += 2 ;
39
- d = - d ;
46
+ d = 1 - d ;
40
47
}
41
48
if (i < 0 ) {
42
49
i = 0 ;
43
- d = - d ;
50
+ d = 1 - d ;
44
51
}
45
52
if (j < 0 ) {
46
53
j = 0 ;
47
- d = - d ;
54
+ d = 1 - d ;
48
55
}
49
56
}
50
57
return result ;
@@ -87,5 +94,5 @@ public int[] findDiagonalOrder(int[][] matrix) {
87
94
return result ;
88
95
}
89
96
}
90
-
97
+
91
98
}
0 commit comments