[array] leetcode - 48. Rotate Image - Medium

leetcode – 48. Rotate Image – Medium

descrition

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

Rotate the image by 90 degrees (clockwise).

Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.


Example 1 :

Given input matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

Example 2:

Given input matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

rotate the input matrix in-place such that it becomes:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

解析

参见代码。小技巧:矩阵的对角线可以唯一确定一个矩阵。

code

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution{
public:
    void rotate(vector<vector<int> >& matrix){
        //rotateNonInplace(matrix);
        rotateNonInplace(matrix);
    }
    /*
        (si,sj) ** (si,sj+k) *** (si,ej)
        *                          *                   
        *                          *
        *                        (si+k,ej)
        (ei-k,sj)                  *
        *                          *
        *                          *
        (ei,sj)*** (ei,ej-k)  ** (ei,ej)     
    */
    // time-O(n^2), space-O(1)
    void rotateInplace(vector<vector<int> >& matrix){
        int n = matrix.size();
        int si = 0, sj = 0; // the top-left corner
        int ei = n-1, ej = n-1; // the down-right corner
        // (si, sj), (ei, ej)

        while(si <= ei && sj<=ej){
            for(int k=0; sj+k<=ej; k++){
                int temp = matrix[si][sj+k];
                matrix[si][sj+k] = matrix[ei-k][sj];
                matrix[ei-k][sj] = matrix[ei][ej-k];
                matrix[ei][ej-k] = matrix[si+k][ej];
                matrix[si+k][ej] = temp;
            }
            si++;
            sj++;
            ei--;
            ej--;
        } 
    }

    // time-O(n^2), space-O(n^2)
    void rotateNonInplace(vector<vector<int> >& matrix){
        int n = matrix.size();
        vector<vector<int> > assit(n, vector<int>(n, 0));

        // put the i-row in matrix to (n-1-i)-column in assit
        for(int i=0; i<n; i++){
            for(int k=0; k<n; k++){
                assit[k][n-1-i] = matrix[i][k];
            }
        }

        // copy assit to matrix
        for(int i=0; i<n; i++){
            for(int j=0; j<n; j++){
                matrix[i][j] = assit[i][j];
            }
        }
    }
};

int main()
{
    return 0;
}

作者:fanling999 链接:https://www.cnblogs.com/fanling999/

    原文作者:fanling999
    原文地址: https://www.cnblogs.com/fanling999/p/7861571.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞