leetcode——48——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) {
         if (matrix.empty())
            return;

        int n = matrix.size();

        //首先,沿主对角线交换元素
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j <= i; j++)
                swap(matrix[i][j], matrix[j][i]);
        }

        for (int i = 0, j = n - 1; i < j; i++, j--)
        {
            for (int k = 0; k < n; k++)
                swap(matrix[k][i], matrix[k][j]);
        }

 

    }
};

你可能感兴趣的:(LeetCode,算法题)