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 temp,n=matrix.size();
if(n%2==0)
{
for(int i=0;i<n/2;i++)
{
for(int j=0;j<n/2;j++)
{
temp=matrix[i][j];
matrix[i][j]=matrix[n-1-j][i];
matrix[n-1-j][i]=matrix[n-1-i][n-1-j];
matrix[n-1-i][n-1-j]=matrix[j][n-1-i];
matrix[j][n-1-i]=temp;
}
}
}
else
{
for(int i=0;i<n/2;i++)
{
for(int j=0;j<n/2;j++)
{
temp=matrix[i][j];
matrix[i][j]=matrix[n-1-j][i];
matrix[n-1-j][i]=matrix[n-1-i][n-1-j];
matrix[n-1-i][n-1-j]=matrix[j][n-1-i];
matrix[j][n-1-i]=temp;
}
}
for(int k=0;k<(n+2)/2;k++)
{
temp=matrix[n/2][k];
matrix[n/2][k]=matrix[n-1-k][n/2];
matrix[n-1-k][n/2]=matrix[n/2][n-1-k];
matrix[n/2][n-1-k]=matrix[k][n/2];
matrix[k][n/2]=temp;
}
}
}
};