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?
思路:先对matrix进行转置,然后reverse每一行中的数据,举个例子
1 2 3……………. 7 4 1………………….1 4 7………………….7 4 1
4 5 6 旋转后变成 8 5 2;而其转置变为 2 5 8,每一行逆序得 8 5 2
7 8 9……………. 9 6 3………………….3 6 9………………….9 6 3
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int size = matrix.size();
for(int i = 0; i < size - 1; ++i)//转置
for(int j = i + 1; j < size; ++j)
swap(matrix[i][j], matrix[j][i]);
for(int i = 0; i < size; ++i){//reverse
int j = 0, k = size - 1;
while(j < k){
swap(matrix[i][j], matrix[i][k]);
j++;
k--;
}
}
}
};