-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateImage.cpp
More file actions
76 lines (70 loc) · 1.98 KB
/
RotateImage.cpp
File metadata and controls
76 lines (70 loc) · 1.98 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<iostream>
#include<vector>
using namespace std;
/*
Greedy: Time Complicity: O(n), Space Complicity: O(1)
Always calculate the farest index the current index
could jump to.
*/
class Solution{
public:
void rotate(vector<vector<int> >& matrix) {
int n = matrix.size();
for(int i = 0; i < n / 2; i++){
for(int j = i; j < n - 1 - i; j++){
int right = j, left = i, pre = matrix[i][j], next;
for(int k = 0; k < 4; k++){
next = matrix[right][n - 1 - left];
matrix[right][n - 1 - left] = pre;
int temp = right;
right = n - 1 - left;
left = temp;
pre = next;
}
}
}
}
};
class Solution2{
public:
void rotate(vector<vector<int> >& matrix) {
int n = matrix.size();
// 水平
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < n; j++) {
swap(matrix[n - 1 - i][j], matrix[i][j]);
}
}
//对角线
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
swap(matrix[j][i], matrix[i][j]);
}
}
}
};
int main(){
int input[][4] = {1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16};
vector<vector<int> > arr2(5, vector<int>(5));
int index=1;
for(int i = 0; i < arr2.size(); i++)
for(int j = 0; j < arr2.size(); j++)
arr2[i][j] = index++;//input[i][j];
Solution solution;
for(int i = 0; i < arr2.size(); i++){
for(int j = 0; j < arr2.size(); j++)
cout << arr2[i][j] << " ";
cout << endl;
}
cout << endl;
solution.rotate(arr2);
for(int i = 0; i < arr2.size(); i++){
for(int j = 0; j < arr2.size(); j++)
cout << arr2[i][j] << " ";
cout << endl;
}
return 0;
}