zoukankan      html  css  js  c++  java
  • 48. 旋转图像

    题目

    代码

    class Solution {
    public:
        void rotate(vector<vector<int>>& matrix) {
            int n=matrix.size();
            for(int i=0;i<n;i++)
            {
                for(int j=0;j<i;j++)
                {
                    std::swap(matrix[i][j],matrix[j][i]);
                }
            }
            for(int i=0;i<n;i++)
            {
                reverse(matrix[i].begin(),matrix[i].end());
            }
        }
    };

    思路

    这道题我当时没想出来,在讨论区看到这个答案的代码非常完美。下面截取一段解释(看懂了这个解释基本也就理解了这个算法的思路,自己在纸上模拟一下2或者3阶的解法步骤即可):

    Best answer to this problem! Although at first I found it really hard to figure out why it works, but now I think I have got the beauty behind the code and here is my understanding.
    Consider the transformation of coordinates in a 4x4 matrix after rotation :
    (0,0) -> (0,3)
    (0,1) -> (1,3)
    (0,2) -> (2,3)
    ...
    and for a NxN matrix, we have the transform :
    ( i , j ) -> ( j , N - i -1 )
    Based on this, you can perform ( i , j ) -> ( j , i ) by transpose the matrix, and reverse each row to perform ( j , i ) -> ( j , N - i - 1).

    It's a little bit hard to figure out why ( i , j ) -> ( j , N - i -1 ) after rotation. From another perspective, imagine that there is a square (side length = n) and it has a rectangular coordinate system along the lower-left corner, and the matrix is plotted on the square. The effects of rotating matrix is equivalent to the rotation and translation of the coordinate system to the lower-right corner of square, and the coordinates of points ( i , j ) on the matrix can be easily calculated to be exactly ( j , N - i -1 ). If still confused, just grab a pen and draw it on paper and you will get it.

    https://github.com/li-zheng-hao
  • 相关阅读:
    zabbix微信报警 风行天下
    centos7环境下的Mysql5.7.22安装 风行天下
    任务计划程序Windows2008及win2016计划任务定时重启 风行天下
    zabbix监控windows磁盘空间 风行天下
    redhat 7安装CentOS 7 yum源 风行天下
    rhel7配置yum的方法 风行天下
    centos7防火墙使用方法 风行天下
    rhel7配置ELK过程 风行天下
    windows巡检 风行天下
    MapX+VB 前一视图功能
  • 原文地址:https://www.cnblogs.com/lizhenghao126/p/11053646.html
Copyright © 2011-2022 走看看