forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
rotate-image.cpp
37 lines (35 loc) · 1.05 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
// Time: O(n^2)
// Space: O(1)
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
const int n = matrix.size();
for (int i = 0; i < n / 2; ++i) {
for (int j = i; j < n - 1 - i; ++j) {
const auto tmp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][i];
matrix[n - 1- j][i] = matrix[n - 1 - i][n - 1 - j];
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
matrix[j][n - 1 - i] = tmp;
}
}
}
};
class Solution2 {
public:
void rotate(vector<vector<int>>& matrix) {
const int n = matrix.size();
// Anti-diagonal mirror.
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n - i; ++j) {
swap(matrix[i][j], matrix[n - 1 - j][n - 1 - i]);
}
}
// Horizontal mirror.
for (int i = 0; i < n / 2; ++i) {
for (int j = 0; j < n; ++j) {
swap(matrix[i][j], matrix[n - 1 - i][j]);
}
}
}
};