LeetCode题解: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?

思路:

可以参见Programming Pearls,很多时候旋转是可以用reverse代替的。

做顺时针90度旋转,可以先转置矩阵,然后对矩阵的每一行进行reverse。

题解:

class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
        const size_t  N = matrix.size();
        // transpose first
        for(size_t i = 0; i < N; ++i)
            for(size_t j = i + 1; j < N; ++j)
                swap(matrix[j][i], matrix[i][j]);
        
        // do reverse on each row
        for(auto& row : matrix)
            reverse(begin(row), end(row));
            
        // we are done
    }
};


你可能感兴趣的:(LeetCode)