zoukankan      html  css  js  c++  java
  • 每日算法37: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?

    原地图像顺时针旋转90度。由于要求空间复杂度是常数,因此应该迭代旋转操作。

    class Solution {
    public:
        void rotate(vector<vector<int> > &matrix) {
            int n = matrix.size();
            int layers = n/2;//图像旋转的圈数
            
            for(int layer = 0;layer < layers;layer++)//每次循环一层,右青色到紫色
             for(int i = layer;i<n-1-layer;i++)//每次可以交换四个元素的位置
             {
                 int temp = matrix[i][layer];//不清楚绘图举例就可以
                 matrix[i][layer] = matrix[n-1-layer][i];
                 matrix[n-1-layer][i] = matrix[n-1-i][n-1-layer];
                 matrix[n-1-i][n-1-layer] = matrix[layer][n-1-i];
                 matrix[layer][n-1-i] = temp;
              }
        }
    };

    以下是网友给出的还有一种方案:


    class Solution {
    public:
        void rotate(vector<vector<int> > &matrix) {
            int i,j,temp;
            int n=matrix.size();
            // 沿着副对角线反转
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n - i; ++j) {
                    temp = matrix[i][j];
                    matrix[i][j] = matrix[n - 1 - j][n - 1 - i];
                    matrix[n - 1 - j][n - 1 - i] = temp;
                }
            }
            // 沿着水平中线反转
            for (int i = 0; i < n / 2; ++i){
                for (int j = 0; j < n; ++j) {
                    temp = matrix[i][j];
                    matrix[i][j] = matrix[n - 1 - i][j];
                    matrix[n - 1 - i][j] = temp;
                }
            }
        }
    };


    版权声明:本文博主原创文章。博客,未经同意不得转载。

  • 相关阅读:
    进制转换
    01背包基础
    6-14 Inspector s Dilemma uva12118(欧拉道路)
    9-4 Unidirectional TSP uva116 (DP)
    8-4 奖品的价值 uva11491(贪心)
    9-1 A Spy in the Metro uva1025 城市里的间谍 (DP)
    8-3 Bits Equalizer uva12545
    8-2 Party Games uva1610 (贪心)
    自动发邮件功能
    窗口截图.py
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4848882.html
Copyright © 2011-2022 走看看