-
Notifications
You must be signed in to change notification settings - Fork 16
/
RotateImage.java
53 lines (46 loc) · 1.65 KB
/
RotateImage.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// https://leetcode.com/problems/rotate-image
// T: O(n ^ 2)
// S: O(1)
public class RotateImage {
private static final class Point {
private final int row;
private final int column;
private Point(int row, int column) {
this.row = row;
this.column = column;
}
}
public void rotate(int[][] matrix) {
final int frames = (matrix.length + 1) / 2;
for (int frame = 0 ; frame < frames ; frame++) {
rotate90Degrees(matrix, frame);
}
}
private void rotate90Degrees(int[][] matrix, int frame) {
for (int i = 0 ; i < matrix.length - 2 * frame - 1 ; i++) {
Point p1 = getCoordinates(frame, 0, matrix.length, i);
int temp1 = get(matrix, p1), temp2;
for (int k = 0 ; k < 4 ; k++) {
Point p2 = getCoordinates(frame, (k + 1) % 4, matrix.length, i);
temp2 = get(matrix, p2);
set(matrix, p2, temp1);
temp1 = temp2;
}
}
}
private int get(int[][] matrix, Point point) {
return matrix[point.row][point.column];
}
private void set(int[][] matrix, Point point, int value) {
matrix[point.row][point.column] = value;
}
private Point getCoordinates(int frame, int k, int size, int shift) {
return switch (k) {
case 0 -> new Point(frame, frame + shift);
case 1 -> new Point(frame + shift, size - 1 - frame);
case 2 -> new Point(size - 1 - frame, size - 1 - frame - shift);
case 3 -> new Point(size - 1 - frame - shift, frame);
default -> null;
};
}
}