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.

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值