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?

    方法一:常规思路: 将图片分为 行数/2 层,然后一层层进行旋转,由外到里。在这个过程中,比较关键的是下标的处理。可从n=3时得出一定的规律。每次旋转时,分析替换的元素对的下标和行、列的关系。如 i=0、j=0时 1:[0][0]换为 7:[2][0]。

    代码如下:

     1 class Solution {
     2 public:
     3     void rotate(vector<vector<int> > &matrix) 
     4     {
     5         int n=matrix.size();
     6         for(int i=0;i<n/2;++i)
     7         {
     8             for(int j=i;j<n-1-i;++j)
     9             {
    10                 int temp=matrix[i][j];
    11                 matrix[i][j]=matrix[n-1-j][i];
    12                 matrix[n-1-j][i]=matrix[n-1-i][n-1-j];
    13                 matrix[n-1-i][n-1-j]=matrix[j][n-1-i];
    14                 matrix[j][n-1-i]=temp;
    15             }
    16         }
    17 
    18     }
    19 };

    方法二:参考Grandyang博客中方法三。其大体的思路是,先求原矩阵的转置矩阵,然后反正转置矩阵中的每一行的元素,即可。转置矩阵:把矩阵A的行换成相应的列,得到的新矩阵称为A的转置矩阵,记作AT 。转置矩阵的得到的方式是如下图所示,沿对角线,绿色箭头两端的元素对调,得到转置矩阵,然后每一行的元素反转,得到最后要求的矩阵。

     代码如下:

     1 class Solution {
     2 public:
     3     void rotate(vector<vector<int> > &matrix) 
     4     {
     5         int n = matrix.size();
     6         for (int i = 0; i < n; ++i) 
     7         {
     8             for (int j = i + 1; j < n; ++j) 
     9             {
    10                 swap(matrix[i][j], matrix[j][i]);
    11             }
    12             reverse(matrix[i].begin(), matrix[i].end());
    13         }
    14     }
    15 };
  • 相关阅读:
    QWrap简介之:EventW Event包装
    QWrap简介之:core_retouch 渲染原生类
    QWrap简介之:youa_retouch 项目个性
    QWrap简介之:Apps 应用 收获果实
    QWrap简介之:Wrap模式
    QWrap简介之:dom_retouch NodeW 勇士装甲
    Activity之间的数据传递
    OpenGL ES Tutorial for Android
    从零开始学习OpenGL ES之一 – 基本概念
    java自定义注解
  • 原文地址:https://www.cnblogs.com/love-yh/p/7100453.html
Copyright © 2011-2022 走看看