[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?

在o(1)space中把题解掉。

思路是每次计算一个像素旋转后所到达的位置,发现四个像素构成了一个旋转的回路。于是只要存储这些像素的值,进行旋转即可。

需要注意循环的起止点。

class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
        int n = matrix.size();
        for(int i = 0; i < n / 2; i++){
            int startColumn = i;
            for(int j = startColumn; j < n - i - 1; j++){
                int lt = matrix[i][j]; // left top corner
                int lb = matrix[n - j - 1][i]; // left bottom corner
                int rt = matrix[j][n - i - 1]; // right top corner
                int rb = matrix[n - i - 1][n - j - 1]; // right bottom corner
                matrix[i][j] = lb;
                matrix[n - j - 1][i] = rb;
                matrix[j][n - i - 1] = lt;
                matrix[n - i - 1][n - j - 1] = rt;
            }
        }
    }
};

Untitled1

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.