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?

 

 

解题分析:

这里,有个小技巧:

首先沿着副对角线翻转一次,然后沿着水平中线翻转一次

或者,首先沿着水平中线翻转一次,然后沿着主对角线翻转一次

Leetcode:Rotate Image 矩阵旋转 

 

class Solution {

public:

    void rotate(vector<vector<int> > &matrix) {

        int n = matrix.size();

        if (n == 0) return;

        for (int i = 0; i < n / 2; ++i) {

            for (int j = 0; j < n; ++j) {

                swap(matrix.at(i).at(j), matrix.at(n-1-i).at(j));

            }

        }

        

        for (int i = 0; i < n; ++i) {

            for (int j = 0; j <= i; ++j) {

                swap(matrix.at(i).at(j), matrix.at(j).at(i));

            }

        }

    }

};

 

你可能感兴趣的:(LeetCode)