题目:
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?
常数空间里完成。
思路:
/*
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3 7 8 9 7 4 1
* 4 5 6 => 4 5 6 => 8 5 2
* 7 8 9 1 2 3 9 6 3
*/
1、先上下翻转,再转置。或者先转置再翻转也可以。
2、直接按周旋转,即每次旋转一周。
代码:
class Solution {
public:
/*
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3 7 8 9 7 4 1
* 4 5 6 => 4 5 6 => 8 5 2
* 7 8 9 1 2 3 9 6 3
*/
void rotate(vector<vector<int> > &matrix)
{
if(matrix.empty())
return;
int row = matrix.size();
for(int i = 0 ; i < row / 2 ; i++)
{
for(int j = 0 ; j < row ; j++)
{
swap(matrix[i][j],matrix[row-i-1][j]);
}
}
for(int i = 0 ; i < row ; i++)
{
for(int j = i ; j < row ; j++)
{
swap(matrix[i][j],matrix[j][i]);
}
}
return ;
}
};
代码2:
class Solution {
public:
/*
* clockwise rotate
* 1 2 3 7 4 1
* 4 5 6 => 8 5 2
* 7 8 9 9 6 3
*/
void rotate(vector<vector<int>>& matrix)
{
int row = matrix.size();
if(row == 0)
return ;
//采用一周一周旋转的方法
for (int i=0; i<row/2; ++i)
{
//每次旋转一周
for (int j=i; j<row-1-i; ++j)
{
int z = matrix[i][j]; //第一周 把 1 临时保存下来
matrix[i][j] = matrix[row-j-1][i];//把7 放到 1 的位置
matrix[row-j-1][i] = matrix[row-i-1][row-j-1]; //把 9 放到 7 的位置
matrix[row-i-1][row-j-1] = matrix[j][row-i-1]; //把 3 放到 9 的位置
matrix[j][row-i-1] = z; //把 1 放到 3 的位置
}
}
}
};