File tree Expand file tree Collapse file tree 2 files changed +69
-3
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +69
-3
lines changed Original file line number Diff line number Diff line change @@ -38,4 +38,69 @@ public int[][] generateMatrix(int n) {
38
38
return matrix ;
39
39
}
40
40
}
41
+
42
+ public static class Solution2 {
43
+ /**
44
+ * My completely original solution on 10/12/2021.
45
+ */
46
+ public int [][] generateMatrix (int n ) {
47
+ int direction = 0 ;
48
+ int [][] matrix = new int [n ][n ];
49
+ int num = 1 ;
50
+ int i = 0 ;
51
+ int j = 0 ;
52
+ int eastBoundary = n ;
53
+ int southBoundary = n ;
54
+ int westBoundary = 0 ;
55
+ int northBoundary = 0 ;
56
+ int limit = n * n ;
57
+ while (num <= limit ) {
58
+ if (direction % 4 == 0 ) {
59
+ //0 means going east
60
+ for (; j < eastBoundary && num <= limit ; j ++) {
61
+ matrix [i ][j ] = num ;
62
+ num ++;
63
+ }
64
+ j --;
65
+ direction ++;
66
+ eastBoundary --;
67
+ i ++;
68
+ }
69
+ if (direction % 4 == 1 ) {
70
+ //1 means going south
71
+ for (; i < southBoundary && num <= limit ; i ++) {
72
+ matrix [i ][j ] = num ;
73
+ num ++;
74
+ }
75
+ i --;
76
+ direction ++;
77
+ southBoundary --;
78
+ j --;
79
+ }
80
+ if (direction % 4 == 2 ) {
81
+ //2 means going west
82
+ for (; j >= westBoundary && num <= limit ; j --) {
83
+ matrix [i ][j ] = num ;
84
+ num ++;
85
+ }
86
+ j ++;
87
+ direction ++;
88
+ westBoundary ++;
89
+ i --;
90
+ }
91
+ if (direction % 4 == 3 ) {
92
+ //3 means going north
93
+ for (; i > northBoundary && num <= limit ; i --) {
94
+ matrix [i ][j ] = num ;
95
+ num ++;
96
+ }
97
+ i ++;
98
+ direction ++;
99
+ northBoundary ++;
100
+ j ++;
101
+ }
102
+ }
103
+ return matrix ;
104
+ }
105
+ }
41
106
}
Original file line number Diff line number Diff line change 7
7
8
8
public class _59Test {
9
9
private static _59 .Solution1 solution1 ;
10
- private static int [][] matrix ;
10
+ private static _59 . Solution2 solution2 ;
11
11
12
12
@ BeforeClass
13
13
public static void setup () {
14
14
solution1 = new _59 .Solution1 ();
15
+ solution2 = new _59 .Solution2 ();
15
16
}
16
17
17
18
@ Test
18
19
public void test1 () {
19
- matrix = solution1 .generateMatrix (6 );
20
- CommonUtils .print2DIntArray (matrix );
20
+ CommonUtils . print2DIntArray ( solution1 .generateMatrix (6 ) );
21
+ CommonUtils .print2DIntArray (solution2 . generateMatrix ( 6 ) );
21
22
}
22
23
}
You can’t perform that action at this time.
0 commit comments