LeetCode:Rotate Image

題目連接html

You are given an n x n 2D matrix representing an image.算法

Rotate the image by 90 degrees (clockwise).this

Follow up:
Could you do this in-place?code


不使用額外的空間順時針旋轉方陣90度htm

例如blog

image  旋轉後變爲image ip

 

算法1leetcode

先將矩陣轉置,而後把轉置後的矩陣每一行翻轉get

image    轉置變爲   image   每一行翻轉變爲 imageit

class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
        int n = matrix.size();
        //轉置
        for(int i = 0; i < n; i++)
            for(int j = i+1; j < n; j++)
                swap(matrix[i][j] , matrix[j][i]);
        //每一行翻轉
        for(int i = 0; i < n; i++)
            for(int j = 0; j < (n>>1); j++)
                swap(matrix[i][j], matrix[i][n-j-1]);
    }
};

 

算法2

能夠見矩陣當作多個環組成,以下4*4的矩陣包括兩個環,第一個環爲1,2,3,4,8,12,16,15,14,13,9,5,1,第二個環爲6,7,11,10。

image

旋轉一個矩陣,至關於把每個環都旋轉。如何旋轉一個環呢?以最外層的環舉例:                      本文地址

旋轉前:image ,旋轉後:image

 

咱們把環分紅3組:{1,4,16,13},{2,8,15,9},{3,12,14,5},每一組中:旋轉後至關於把原來的數字移動到同組中下一個數字的位置

 

對於一個n*n的矩陣能夠分紅n/2(向上取整)個環來旋轉;對於邊長爲len的環,能夠分紅len-1組來旋轉。

class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
        int n = matrix.size();
        if(n == 0)return;
        for(int i = 0, len = n; i < n/2; i++, len -= 2)
        {//n/2 爲旋轉的圈數,len爲第i圈中正方形的邊長
            int m = len - 1;
            for(int j = 0; j < m; j++)
            {
                int tmp = matrix[i][i+j];
                matrix[i][i+j] = matrix[i+m-j][i];
                matrix[i+m-j][i] = matrix[i+m][i+m-j];
                matrix[i+m][i+m-j] = matrix[i+j][i+m];
                matrix[i+j][i+m] = tmp;
            }
        }
    }
};

【版權聲明】轉載請註明出處:http://www.cnblogs.com/TenosDoIt/p/3768734.html

相關文章
相關標籤/搜索