You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
int s = matrix.size() - 1;
for (int n = s, c = 0; n > 0; n -= 2, ++c) {
int tmp;
for (int i = 0; i < n; ++i) {
// clockwise
tmp = matrix[c][i + c];
matrix[c][i + c] = matrix[s - i - c][c];
matrix[s - i - c][c] = matrix[s - c][s - i - c];
matrix[s - c][s - i - c] = matrix[i + c][s - c];
matrix[i + c][s - c] = tmp;
// anticlockwise
/*tmp = matrix[c][i + c];
matrix[c][i + c] = matrix[i + c][s - c];
matrix[i + c][s - c] = matrix[s - c][s - i - c];
matrix[s - c][s - i - c] = matrix[s - i - c][c];
matrix[s - i - c][c] = tmp;*/
// print here to observ how it works
}
}
}
};
本文介绍了一个用于二维矩阵(图像)的90度顺时针旋转算法,并提供了C++实现代码。该算法通过逐层旋转的方式实现了原地(in-place)操作,有效减少了额外的空间开销。
2166

被折叠的 条评论
为什么被折叠?



