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?

分析

本地使得二维矩阵,旋转90角度。

通过实际数据分析,通过两个步骤的元素交换可实现目标:

  1. 按照主对角线,将对称元素交换
  2. 按照列,将对称列元素全部交换

即可达到,使得二维矩阵,本地旋转90个角度。

AC代码

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]);
        }
    }
};

GitHub测试程序源码

原文地址:https://www.cnblogs.com/shine-yr/p/5214888.html