@@ -10,41 +10,48 @@ public static class Solutoin1 {
1010 /**
1111 * Reference: https://discuss.leetcode.com/topic/77865/concise-java-solution/2
1212 * 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.
1419 */
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 ) {
1822 return new int [0 ];
1923 }
20- int m = matrix .length ;
21- int n = matrix [0 ].length ;
24+ int m = mat .length ;
25+ int n = mat [0 ].length ;
2226 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 }};
2430 int i = 0 ;
2531 int j = 0 ;
32+ int d = 0 ;
2633 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 ] ;
3037
3138 if (i >= m ) {
3239 i = m - 1 ;
3340 j += 2 ;
34- d = - d ;
41+ d = 1 - d ;
3542 }
3643 if (j >= n ) {
3744 j = n - 1 ;
3845 i += 2 ;
39- d = - d ;
46+ d = 1 - d ;
4047 }
4148 if (i < 0 ) {
4249 i = 0 ;
43- d = - d ;
50+ d = 1 - d ;
4451 }
4552 if (j < 0 ) {
4653 j = 0 ;
47- d = - d ;
54+ d = 1 - d ;
4855 }
4956 }
5057 return result ;
@@ -87,5 +94,5 @@ public int[] findDiagonalOrder(int[][] matrix) {
8794 return result ;
8895 }
8996 }
90-
97+
9198}
0 commit comments