C ++ algorithms: --- Flip rotate the image matrix

topic:

Given an n × n represents a two-dimensional matrix image. The image is rotated 90 degrees clockwise.

Description:

You have to rotate the image in place, which means you need to directly modify the two-dimensional matrix input. Do not use another matrix to rotate an image.

Example 1:

Given = Matrix
[
[l, 2,3],
[4,5,6],
[7,8,9]
],

In situ rotation of the input matrix, so that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

Example 2:

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

In situ rotation of the input matrix, so that it becomes:
[
[15, 13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7, 10 ]
]

Ideas: first transposed matrix, then flip each line. This simple method has been able to achieve the optimal time complexity of O (N ^ 2).

Code:

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int i, j;
        for(i = 0;i<matrix.size();i++)
            for(j=i;j<matrix.size();j++)
                 RotateMatrix(matrix,i,j);
        
        for(i=0;i<matrix.size();i++)
            for(j=0;j<matrix.size()/2;j++)
                RowMatrix(matrix,i,j);
    }
    
private:
   void RotateMatrix(vector<vector<int>>& matrix, int i, int j){
       int temp = matrix[i][j];
       matrix[i][j] = matrix[j][i];
       matrix[j][i] = temp;
   }
    
   void RowMatrix(vector<vector<int>>& matrix,int i,int j){
       int temp = matrix[i][j];
       matrix[i][j] = matrix[i][matrix.size()-j-1];
       matrix[i][matrix.size()-j-1] = temp;
   }
       
};

Guess you like

Origin blog.csdn.net/qq_31820761/article/details/91859367