-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotate Image.cpp
61 lines (48 loc) · 1.32 KB
/
Rotate Image.cpp
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
54
55
56
57
58
59
60
61
approach 1-> brute force
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();;
vector<vector<int>> mat(n, vector<int>(n,0));
for(int i=0 ; i<n ; i++) {
// taking up the first row
// and making it the last column
int col_indx = n-i-1;
for(int j=0 ; j<n ; j++) {
mat[j][col_indx] = matrix[i][j];
}
}
for(int i=0 ; i<n ; i++) {
for(int j=0 ; j<n ; j++) {
matrix[i][j] = mat[i][j];
}
}
}
};
// optimized approach
/*
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3 7 8 9 7 4 1
* 4 5 6 => 4 5 6 => 8 5 2
* 7 8 9 1 2 3 9 6 3
*/
class Solution {
public:
void swap(int &a,int &b) {
int temp = a;
a = b;
b = temp;
}
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
// reversing-> upside down (ikr)
reverse(matrix.begin(), matrix.end());
// swapping the symmetry
for(int i=0 ; i<n ; i++) {
for(int j=i+1 ; j<n ; j++) {
swap(matrix[i][j] , matrix[j][i]);
}
}
}
};