[LeetCode] 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?

 

思路一:

b[i][j] = a[n-1-j][i], 构造b,然后将b赋值给a,空间复杂度O(n*n)

class Solution {
    public:
        void rotate(vector<vector<int> > &matrix)
        {   
            size_t n = matrix.size();
            vector<vector<int> > re; 
            vector<int> b;
            b.resize(n);

            for(int i = 0; i < n; i ++) 
                re.push_back(b);


            for(int i = 0; i < n; i ++) 
                for(int j = 0; j < n; j ++) 
                {   
                  re[i][j] = matrix[n-j-1][i]; 
                }   

            for(int i = 0; i < n; i ++) 
                for(int j = 0; j < n; j ++) 
                  matrix[i][j] = re[i][j]; 
        }   
};

思路二:旋转90°= 第一步, 沿着副对角线翻转+ 第二步,沿着水平中轴线翻转,空间复杂度O(1)

 

class Solution {
    public:
    #if 0
        void rotate(vector<vector<int> > &matrix)
        {   
            size_t n = matrix.size();
            vector<vector<int> > re; 
            vector<int> b;
            b.resize(n);

            for(int i = 0; i < n; i ++) 
                re.push_back(b);


            for(int i = 0; i < n; i ++) 
                for(int j = 0; j < n; j ++) 
                {   
                  re[i][j] = matrix[n-j-1][i]; 
                }   

            for(int i = 0; i < n; i ++) 
                for(int j = 0; j < n; j ++) 
                  matrix[i][j] = re[i][j]; 
        }  
    #endif
            public:
        void rotateFromDiagonal (vector<vector<int> > &matrix)
        {
            size_t n = matrix.size();
            int tmp;
            for(int i = 0; i < n; i ++)
                for(int j = 0; j <  n-i; j ++)
                {
                    tmp = matrix[i][j];
                    matrix[i][j] = matrix[n-j-1][n-i-1];
                    matrix[n-j-1][n-i-1] = tmp;
                }
        }

        void rotateFromHorizon(vector<vector<int> > &matrix)
        {
            size_t n = matrix.size();
            int tmp;
            for(int i = 0; i < n/2; i ++)
                for(int j = 0; j < n; j ++)
                {
                    tmp = matrix[i][j];
                    matrix[i][j] = matrix[n-1-i][j];
                    matrix[n-1-i][j] = tmp;
                }
        }

        void rotate(vector<vector<int> > &matrix)
        {
            rotateFromDiagonal(matrix);
            rotateFromHorizon(matrix);
        }
};

 

posted @ 2015-03-03 14:07  穆穆兔兔  阅读(214)  评论(0编辑  收藏  举报