LeetCode:Rotate Image

Rotate Image


Total Accepted: 58066  Total Submissions: 172733  Difficulty: Medium

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?

Hide Tags
  Array














思路:

可以自己拿张方形的纸试一下:

1.先将纸沿副对角线(右上到左下)对折;

2.再将纸沿中心横线对折,即为纸顺时针旋转90度后的结果。


code:

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


你可能感兴趣的:(LeetCode,image,rotate)