0%

48. Rotate Image

48. Rotate Image

动态规划
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for(size_t i = 0; i < (n + 1) / 2; ++i)
{
for(size_t j = 0; j < n / 2; ++j)
{
int tmp = 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] = matrix[i][j];
matrix[i][j] = tmp;
}
}
}
};

抄de

转置 + 翻转

transpose and reflect in linear algebra

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for(int i = 0; i < n; ++i)
for(int j = i; j < n; ++j)
swap(matrix[i][j], matrix[j][i]);

for(int i = 0; i < n; ++i)
for(int j = 0; j < n / 2; ++j)
swap(matrix[i][j], matrix[i][n - j - 1]);
}
};
顺序反过来

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for(int i = 0; i < n; ++i)
for(int j = 0; j < n / 2; ++j)
swap(matrix[i][j], matrix[i][n - j - 1]);
for(int i = 0; i < n; ++i)
for(int j = 0; j <= n - i - 1; ++j)
swap(matrix[i][j], matrix[n - j - 1][n - i - 1]);
}
};