zoukankan      html  css  js  c++  java
  • 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?
    

    The rotation can be performed in layers, where you perform a cyclic swap on the edges on 

    each layer In the frst for loop, we rotate the frst layer (outermost edges) We rotate the
    edges by doing a four-way swap frst on the corners, then on the element clockwise from the
    edges, then on the element three steps away
    Once the exterior elements are rotated, we then rotate the interior region’s edge

    class Solution {
    public:
        void rotate(vector<vector<int> > &matrix) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            int n = matrix.size();
            if(n < 2) return ;
            for(int lay = 0 ; lay < n/2; lay ++){
                  int first = lay ;
                  int last = n - 1 - lay;
                for(int i = first; i< last; i++){
                    int offset = i - first;
                    //store the top
                    int top = matrix[first][i] ;
                    //left to top
                     matrix[first][i] = matrix[last - offset][first];
                     //bottom to left
                     matrix[last - offset][first] = matrix[last][last- offset];
                     //right to bottom
                     matrix[last][last - offset] = matrix[i][last];
                     //top to right
                     matrix[i][last] = top;        
                }
            }            
        }
    };
  • 相关阅读:
    JUnit4.13环境配置
    OO第5-7次作业总结
    电梯的一点浅优化
    C++变量作用域、生存期、存储类别
    最后一次OO博客
    OO第三次总结
    OO第二次总结
    OO第一次总结
    POJ3934
    POJ刷题计划
  • 原文地址:https://www.cnblogs.com/graph/p/3229056.html
Copyright © 2011-2022 走看看