Skip to content

Commit 2ee3708

Browse files
refactor 48
1 parent 2fd3605 commit 2ee3708

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,4 +80,28 @@ public void rotate(int[][] matrix) {
8080
}
8181
}
8282

83+
public static class Solution3 {
84+
public void rotate(int[][] matrix) {
85+
int n = matrix.length;
86+
for (int i = 0; i < n / 2; i++) {
87+
for (int j = i; j < n - i - 1; j++) {
88+
//save the top
89+
int top = matrix[i][j];
90+
91+
//move left to top
92+
matrix[i][j] = matrix[n - 1 - j][i];
93+
94+
//move bottom to left
95+
matrix[n - 1 - j][i] = matrix[n - i - 1][n - 1 - j];
96+
97+
//move right to bottom
98+
matrix[n - i - 1][n - 1 - j] = matrix[j][n - i - 1];
99+
100+
//move top to right
101+
matrix[j][n - i - 1] = top;
102+
}
103+
}
104+
}
105+
}
106+
83107
}

src/test/java/com/fishercoder/_48Test.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@
88
public class _48Test {
99
private static _48.Solution1 solution1;
1010
private static _48.Solution2 solution2;
11+
private static _48.Solution3 solution3;
1112
private static int[][] matrix;
1213

1314
@BeforeClass
1415
public static void setup() {
1516
solution1 = new _48.Solution1();
1617
solution2 = new _48.Solution2();
18+
solution3 = new _48.Solution3();
1719
}
1820

1921
@Test
@@ -59,4 +61,16 @@ public void test4() {
5961
solution1.rotate(matrix);
6062
CommonUtils.print2DIntArray(matrix);
6163
}
64+
65+
@Test
66+
public void test5() {
67+
matrix = new int[][]{
68+
{1, 2, 3, 4},
69+
{5, 6, 7, 8},
70+
{9, 10, 11, 12},
71+
{13, 14, 15, 16}
72+
};
73+
solution3.rotate(matrix);
74+
CommonUtils.print2DIntArray(matrix);
75+
}
6276
}

0 commit comments

Comments
 (0)