48. 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:

关键在于找到旋转90°的关系
假设 
a:(i,j),那么
b: (j,n-1-i)
c: (n-1-j,i)
d: (n-1-i,n-1-j)
依次交换就是了,循环的方式是:
从最外层一圈操作,然后往内圈重复步骤
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int n = matrix.size();
        for(int i = 0; i < n/2; ++i){
            for(int j = i; j < n - 1 -i; ++j){
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[n-1-j][i];
                matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
                matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
                matrix[j][n-1-i] = tmp;
            }
        }
    }
};

方法2

先将矩阵转置,然后对每一行逆序
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
    void rotate(vector<vector<int>>& m) {
        int n = m.size();
        for(int i=0; i<n; i++)
            for(int j=0; j<i; j++)
                swap(m[i][j], m[j][i]);
         
        for(int i=0; i<n; i++)
            reverse(m[i].begin(), m[i].end());
    }
};

类似的,如果想要得到逆时针90度,那么就先对每一行求逆,然后再转置






posted @ 2017-02-09 20:42  copperface  阅读(162)  评论(0编辑  收藏  举报