zoukankan      html  css  js  c++  java
  • 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?
    中文题目:
    有一个NxN整数矩阵,请编写一个算法,将矩阵顺时针旋转90度。
    给定一个NxN的矩阵,和矩阵的阶数N,请返回旋转后的NxN矩阵,保证N小于等于300。
    分析:
    过程如下图所示:

    step1:

    区域1和2内元素互换
    step1的结果为:
    step1的结果

    step2:

    区域1和4内元素互换
    step2的结果为:
    step2的结果

    step3:

    区域3和4内元素互换
    step3的结果

    step4:

    上图的圆圈中的元素按照上述顺序互换

    这样,一层结束了;

    step5:

    在二维数组的内层继续执行step1–step4,直到最内层结束;

    代码如下:

    class Rotate {
    public:
        void swap(int &a,int &b)
    {
        int temp = a;
        a = b;
        b = temp;
    }
        vector<vector<int> > rotateMatrix(vector<vector<int> > mat, int n) {
        if(n == 1 || n == 0)
        return mat;
    
        int up  = 0;
        int right = n-1;
        int down = n-1;
        int left = 0;
    
        while(up < down && left < right)
        {
            //1,2 swap
            int begin1 = up + 1;
            for(int i = left + 1;i < right;i++)
            {
                swap(mat[up][i],mat[begin1++][right]);
            }
            //1 4 swap
            begin1 = down - 1;
            for(int i = left + 1;i < right;i++)
            {
                swap(mat[up][i],mat[begin1--][left]);
            }
            //3 4 swap
            begin1 = up + 1;
            for(int i = left + 1;i < right;i++)
            {
                swap(mat[down][i],mat[begin1++][left]);
            }
            //圆圈内的四个角上的元素互换
            swap(mat[up][left],mat[up][right]);
    
            swap(mat[up][left],mat[down][left]);
    
            swap(mat[down][left],mat[down][right]);
    
            up++;
            down--;
            left++;
            right--;
        }
        return mat; 
        }
    };

    算法实现在数组本地实现,空间复杂度为O(1).

  • 相关阅读:
    JavaScript Window
    3.1.3 背景音乐播放技术
    6.1 多媒体相关基本概念及计算问题
    11.5 知识产权考点讲解
    第15课 TortoiseGit程序操作介绍
    第16课 “远程 Git文档库” 的基础操作
    第11课 Git GUI程序的基本功能
    第12课 使用Git GUI
    第13课 SmartGit程序操作介绍
    第14课 SourceTree程序操作介绍
  • 原文地址:https://www.cnblogs.com/sunp823/p/5601403.html
Copyright © 2011-2022 走看看