首页 > 代码库 > Leetcode:Rotate Image 旋转图片

Leetcode: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?

刚开始没有思路,但是自己举了几个简单的栗子才看出规律:需要一圈儿一圈儿的变换位置。有两层for循环:外层控制圈儿数;内层控制交换的元素位置。每一次都有四个元素需要交换。代码如下:

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



Leetcode:Rotate Image 旋转图片