Rotate Image
*You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).*
解题过程 :
用一个二维数组来模拟一个图像,要把图像顺时针旋转90度,旋转中心为图像的中心。基本思路是把图片分为行数/2层,然后一层层进行旋转,每一层有上下左右四个列,然后目标就是把上列放到右列,右列放到下列,下列放到左列,左列放回上列,中间保存一个临时变量即可。
public: void rotate(vector<vector<int>>& matrix) {
if(matrix.size()==0)
return;
int layerNum = matrix.size()/2;
for(int layer=0;layer<layerNum;layer++)
{
for(int i=layer;i<matrix.length-layer-1;i++)
{
int temp = matrix[layer][i];
matrix[layer][i] = matrix[matrix.length-1-i][layer];
matrix[matrix.length-1-i][layer] = matrix[matrix.length-1-layer][matrix.length-1-i];
matrix[matrix.length-1-layer][matrix.length-1-i] = matrix[i][matrix.length-1-layer];
matrix[i][matrix.length-1-layer] = temp;
}
}
}