Leetcode 48. Rotate Image矩阵顺时针,逆时针90度总结

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Given input matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

Example 2:

Given input matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

rotate the input matrix in-place such that it becomes:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

题目链接:https://leetcode.com/problems/rotate-image/

class Solution {
public:
    void rotate(vector<vector<int>>& a) {
        int n = a.size();
    for(int i=0; i<n; ++i)
        for(int j=0; j<n-i; ++j)
            swap(a[i][j], a[n-1-j][n-1-i]);

    for(int i=0; i<n/2; ++i)
        for(int j=0; j<n; ++j)
            swap(a[i][j], a[n-1-i][j]);
    }
};

解释一下其中的原理:

矩阵顺时针旋转90度可以分两步走。 第一步交换 / (反向对角线) 对角线两侧的对称元素,第二步交换第i行和第n-1-i行,即得到结果。 看图示:(如果是顺时针,第一步交换主对角线两侧的对称元素,第二步交换第i行和第n-1-i行,即得到结果。)

矩阵A:

原理:其实这样是逆时针旋转了270度,证明过程我就省了

我自己也重新写了个矩阵顺时针转90度后再逆时针旋转复原的程序:

#include<bits/stdc++.h>
using namespace std;

void clockwise(vector<vector<int>> &m)
{
    int n=m.size();
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n-i;j++)
        {
            swap(m[i][j],m[n-1-j][n-1-i]);
        }
    }
    for(int i=0;i<n/2;i++)
    {
        for(int j=0;j<n;j++)
        {
            swap(m[i][j],m[n-1-i][j]);
        }
    }
}

void transpose(vector<vector<int>> &m)
{
    int n=m.size();
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<i;j++)
        {
            swap(m[i][j],m[j][i]);
        }
    }
    for(int i=0;i<n/2;i++)
    {
        for(int j=0;j<n;j++)
        {
            swap(m[i][j],m[n-1-i][j]);
        }
    }
}
int main(void)
{
    vector<vector<int>> matrix;
    int c=10;
    for(int i=0;i<4;i++)
    {
        vector<int> tmp;
        for(int j=0;j<4;j++)
        {
            tmp.push_back(c);
            c++;
        }
        matrix.push_back(tmp);
    }
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            cout<<matrix[i][j]<<" ";
        }
        cout<<endl;
    }
    cout<<endl;
    clockwise(matrix);
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            cout<<matrix[i][j]<<" ";
        }
        cout<<endl;
    }
    cout<<endl;
    transpose(matrix);
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            cout<<matrix[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}

参考链接:https://blog.csdn.net/qq_26525215/article/details/52076488

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/86235928