Skip to content

Commit f79bbc1

Browse files
refactor 59
1 parent 56d2949 commit f79bbc1

File tree

2 files changed

+69
-3
lines changed

2 files changed

+69
-3
lines changed

src/main/java/com/fishercoder/solutions/_59.java

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,69 @@ public int[][] generateMatrix(int n) {
3838
return matrix;
3939
}
4040
}
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+
}
41106
}

src/test/java/com/fishercoder/_59Test.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,17 @@
77

88
public class _59Test {
99
private static _59.Solution1 solution1;
10-
private static int[][] matrix;
10+
private static _59.Solution2 solution2;
1111

1212
@BeforeClass
1313
public static void setup() {
1414
solution1 = new _59.Solution1();
15+
solution2 = new _59.Solution2();
1516
}
1617

1718
@Test
1819
public void test1() {
19-
matrix = solution1.generateMatrix(6);
20-
CommonUtils.print2DIntArray(matrix);
20+
CommonUtils.print2DIntArray(solution1.generateMatrix(6));
21+
CommonUtils.print2DIntArray(solution2.generateMatrix(6));
2122
}
2223
}

0 commit comments

Comments
 (0)