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
  • 相关阅读:
    格式化Format使用
    ASP.NET几种清除页面缓存的方法
    repeater中分页aspnetpager是遇到的问题
    利用正则表达式去掉html代码
    ASP.NET母版页中调用内容页的方法和web用户控件调用.aspx页面里的方法
    PHP常用代码大全
    用 JA Transmenu 模块做多级弹出菜单
    简单的 "改变" joomla 后台administrator目录
    数据库设计中的14个技巧
    Joomla模板制作教程(转)
  • 原文地址:https://www.cnblogs.com/lizhenghao126/p/11053646.html
Copyright © 2011-2022 走看看