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?
剥洋葱大法~注意有时候算层数时候要记得处理余下的一层,这题不需要。例如size=5,一共有两个外层再加当中的一个点,那个点不用rotate,不作处理。
但是 Spiral Matrix 那题当中那层就需要特别处理一下了。
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int size = matrix.size();
int layer = size/2;
for(int i=0;i<layer;i++)
{
for(int j=i;j<size-i-1;j++)
{
int tmp_A = matrix[i][j];
int tmp_B = matrix[j][size-i-1];
int tmp_C = matrix[size-1-i][size-j-1];
int tmp_D = matrix[size-1-j][i];
matrix[i][j] = tmp_D;
matrix[j][size-i-1] = tmp_A;
matrix[size-1-i][size-j-1] = tmp_B;
matrix[size-1-j][i] = tmp_C;
}
}
}
};