每日算法37:Rotate Image (图像旋转)

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<vector<int> > &matrix) {
        int n = matrix.size();
        int layers = n/2;//图像旋转的圈数
        
        for(int layer = 0;layer < layers;layer++)//每次循环一层,右青色到紫色
         for(int i = layer;i<n-1-layer;i++)//每次可以交换四个元素的位置
         {
             int temp = matrix[i][layer];//不清楚绘图举例就可以
             matrix[i][layer] = matrix[n-1-layer][i];
             matrix[n-1-layer][i] = matrix[n-1-i][n-1-layer];
             matrix[n-1-i][n-1-layer] = matrix[layer][n-1-i];
             matrix[layer][n-1-i] = temp;
          }
    }
};

以下是网友给出的还有一种方案:


class Solution {
public:
    void rotate(vector<vector<int> > &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;
            }
        }
    }
};


版权声明:本文博主原创文章。博客,未经同意不得转载。

posted @ 2015-09-30 12:49  mengfanrong  阅读(409)  评论(0编辑  收藏  举报