-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathRotateImage.java
More file actions
41 lines (35 loc) · 1.11 KB
/
RotateImage.java
File metadata and controls
41 lines (35 loc) · 1.11 KB
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
public class RotateImage {
public void rotate(int[][] matrix) {
int n = matrix.length;
int[][] rotated = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
rotated[i][n - 1 - j] = matrix[j][i];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = rotated[i][j];
}
}
}
}
// in place solution
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
//Flip along the diagonal, left-bottom and right-top
for (int i = 0; i < n; i++)
for (int j = 0; j < n - 1 - i; j++)
swap(matrix, i, j, n - 1 - j, n - 1 - i);
for (int i = 0; i < n / 2; i++)
for (int j = 0; j < n; j++)
swap(matrix, i, j, n - 1 - i, j);
}
// Flip along the middle row
public void swap(int[][] matrix, int i1, int j1, int i2, int j2) {
int tmp = matrix[i1][j1];
matrix[i1][j1] = matrix[i2][j2];
matrix[i2][j2] = tmp;
}
}