您的位置:首页 > 其它

LeetCode:Rotate Image

2016-01-23 21:00 253 查看


Rotate Image

My Submissions

Question

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;
        }
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: