-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path48. Rotate Image
52 lines (45 loc) · 1.47 KB
/
48. Rotate Image
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
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
//Transpose
for(int i = 0; i < n; i++) {
for(int j = i; j < n; j++) {
//Swap matrix[i][j] with matrix[j][i]
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
//Reverse of rows
for(int i = 0; i < n; i++) {
for(int j = 0; j < n/2; j++) {
//Swap matrix[i][j] with matrix[i][n-j-1]
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n-j-1];
matrix[i][n-j-1] = temp;
}
}
}
}
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
int layers = n/2;
for(int layer = 0; layer < layers; layer++) {
int start = layer;
int end = n-1-layer;
for(int i = start; i < end; i++) {
//top in temp
int temp = matrix[start][i];
//left in top
matrix[start][i] = matrix[n-1-i][start];
//bottom in left
matrix[n-1-i][start] = matrix[end][n-1-i];
//right in bottom
matrix[end][n-1-i] = matrix[i][end];
//top in right
matrix[i][end] = temp;
}
}
}
}