码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Rotate Image

时间:2015-03-03 14:55:40      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

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);
        }
};

 

[LeetCode] Rotate Image

标签:

原文地址:http://www.cnblogs.com/diegodu/p/4310811.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!