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


有两种方法。

方法一:直接计算法。直接算出旋转前后的对应关系。

方法二:间接法。原矩阵到转置矩阵是很容易计算的,那么从转置矩阵到选择矩阵就只需要reverse每行的元素就可。

方法一的代码如下:

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 t = 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] = t;  
            }  
    }  
};


你可能感兴趣的:(LeetCode)