首页 > 代码库 > 每日算法之三十七: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?

原地图像顺时针旋转90度。因为要求空间复杂度是常数,因此应该迭代旋转操作。

class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
        int n = matrix.size();
        int layers = n/2;//图像旋转的圈数
        
        for(int layer = 0;layer < layers;layer++)//每次循环一层,右青色到紫色
         for(int i = layer;i<n-1-layer;i++)//每次能够交换四个元素的位置
         {
             int temp = matrix[i][layer];//不清楚画图举例即可
             matrix[i][layer] = matrix[n-1-layer][i];
             matrix[n-1-layer][i] = matrix[n-1-i][n-1-layer];
             matrix[n-1-i][n-1-layer] = matrix[layer][n-1-i];
             matrix[layer][n-1-i] = temp;
          }
    }
};

下面是网友给出的另一种方案:


class Solution {
public:
    void rotate(vector<vector<int> > &matrix) {
        int i,j,temp;
        int n=matrix.size();
        // 沿着副对角线反转
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n - i; ++j) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[n - 1 - j][n - 1 - i];
                matrix[n - 1 - j][n - 1 - i] = temp;
            }
        }
        // 沿着水平中线反转
        for (int i = 0; i < n / 2; ++i){
            for (int j = 0; j < n; ++j) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[n - 1 - i][j];
                matrix[n - 1 - i][j] = temp;
            }
        }
    }
};