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 n = matrix.size();
if (n < 2) return;
int i = 0, j = n-1;
//首先水平方向倒序
while (i < j)
{
swap(matrix[i], matrix[j]);
i++; j--;
}
//再沿主对角线翻转
for (int x = 0; x < n; x++)
{
for (int y = x+1; y < n; y++)
swap(matrix[x][y], matrix[y][x]);
}
}
};