• [LeetCode] Rotate Image n-by-n矩阵顺时针旋转


    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?

    Hide Tags
     Array
     
      一题严格的数组逻辑操作问题,考虑认真就好,思路:
     
     
    1 2 3 1
    3 4 4 2
    2 4 4 3
    1 3 2 1
    如上表,一共有两圈,对于n 来说,圈数为(n+1)/2,从外圈到内圈,转换了一圈后到下一圈。
     
    我写的代码用了长度len ,其实写j=i 会方便很多。
    需要计算好下标,有个简单的确认,一次转换中的4个数,不相邻的两个数的对应下标和为定值(n-1),例如一个是<i,j>,另一个就是<n-1  -i,n-1  -j>,利用这个规律其实只要确认两个就行。
    代码如下:
     1 #include <iostream>
     2 #include <vector>
     3 #include <iterator>
     4 using namespace std;
     5 
     6 class Solution {
     7 public:
     8     void rotate(vector<vector<int> > &matrix) {
     9         int n =matrix.size();
    10         if(n<2) return ;
    11         for(int i=0;i<(n+1)/2;i++){
    12             for(int len=0;len<=n-2*(i+1);len++){
    13                 int temp = matrix[i][i+len];
    14                 matrix[i][i+len] = matrix[n-1-i-len][i];
    15                 matrix[n-1-i-len][i] = matrix[n-1-i][n-1-i-len];
    16                 matrix[n-1-i][n-1-i-len] = matrix[i+len][n-i-1];
    17                 matrix[i+len][n-i-1] = temp;
    18             }
    19         }
    20     }
    21 };
    22 
    23 int main()
    24 {
    25     vector<vector<int> > matrix;
    26     vector<int> tempm;
    27     int cnt =1;
    28     for(int i=1;i<9;i++){
    29         for(int j=1;j<9;j++)
    30             tempm.push_back(cnt++);
    31         matrix.push_back(tempm);
    32         tempm.clear();
    33     }
    34     Solution sol;
    35     sol.rotate(matrix);
    36     for(int i=0;i<matrix.size();i++){
    37         copy(matrix[i].begin(),matrix[i].end(),ostream_iterator<int>(cout," "));
    38         cout<<endl;
    39     }
    40 
    41     return 0;
    42 }
    View Code
     
  • 相关阅读:
    IIS6.0远程命令执行
    非结构化和结构化数据提取
    Data Binding on Android
    微前端 [ 日常笔记 ]
    吴裕雄 python 机器学习-NBYS(2)
    吴裕雄 python 机器学习-NBYS(1)
    吴裕雄 python 爬虫(4)
    吴裕雄 python 爬虫(3)
    吴裕雄 python 爬虫(2)
    吴裕雄 python 爬虫(1)
  • 原文地址:https://www.cnblogs.com/Azhu/p/4128361.html
Copyright © 2020-2023  润新知