首页 > 代码库 > 【Leetcode】Rotate Image

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

思路:第一种思路是一层一层的进行旋转,比较直观;第二种思路则比较取巧,首先沿着副对角线翻转一次,然后沿着水平中线翻转一次。

代码一:

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 - i - 1;j++)
            {
                int temp = 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] = temp;
            }
    }
};

代码二:

// LeetCode, Rotate Image
// 思路1,时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
	void rotate(vector<vector<int>>& matrix) {

		const int n = matrix.size();
		
		for (int i = 0; i < n; ++i) // 沿着副对角线反转
			for (int j = 0; j < n - i; ++j)
				swap(matrix[i][j], matrix[n - 1 - j][n - 1 - i]);
		
		for (int i = 0; i < n / 2; ++i) // 沿着水平中线反转
			for (int j = 0; j < n; ++j)
				swap(matrix[i][j], matrix[n - 1 - i][j]);
	}
};