LeetCode OJ:Rotate Image

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?

算法思想:

对于这样一张图

1    2    3

4    5    6

7    8    9

旋转90度也就是将1到3位置,3到9位置,9到7位置,最后7再到1位置,然后2到6位置,6到8位置,8到4位置,最后4再到2位置,所以我们只需对1和2处理就行了。

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

answer2

先沿副对角线反转,再沿水平中线反转

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

answer3

或者是先沿主对角线反转,再沿竖直中线反转

class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
        const 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/2; ++j)  
                swap(matrix[i][j],matrix[i][n-1-j]);
    }
};


你可能感兴趣的:(LeetCode)