每日算法之三十七:Rotate Image (图像旋转)

2015-07-24 05:49:33 · 作者: · 浏览: 6

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?

原地图像顺时针旋转90度。因为要求空间复杂度是常数,因此应该迭代旋转操作。

\

class Solution {
public:
    void rotate(vector
  
    > &matrix) {
        int n = matrix.size();
        int layers = n/2;//图像旋转的圈数
        
        for(int layer = 0;layer < layers;layer++)//每次循环一层,右青色到紫色
         for(int i = layer;i
   
    
下面是网友给出的另一种方案:

\

class Solution {
public:
    void rotate(vector
     
       > &matrix) {
        int i,j,temp;
        int n=matrix.size();
        // 沿着副对角线反转
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n - i; ++j) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[n - 1 - j][n - 1 - i];
                matrix[n - 1 - j][n - 1 - i] = temp;
            }
        }
        // 沿着水平中线反转
        for (int i = 0; i < n / 2; ++i){
            for (int j = 0; j < n; ++j) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[n - 1 - i][j];
                matrix[n - 1 - i][j] = temp;
            }
        }
    }
};