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?
本地使得二维矩阵,旋转90角度。
通过实际数据分析,通过两个步骤的元素交换可实现目标:
即可达到,使得二维矩阵,本地旋转90个角度。
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
if (matrix.empty())
return;
int n = matrix.size();
//首先,沿主对角线交换元素
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= i; j++)
swap(matrix[i][j], matrix[j][i]);
}
for (int i = 0, j = n - 1; i < j; i++, j--)
{
for (int k = 0; k < n; k++)
swap(matrix[k][i], matrix[k][j]);
}
}
};
GitHub测试程序源码