LeetCode:48. Rotate Image

博客围绕LeetCode 48题,即顺时针旋转等宽高矩阵展开。介绍了两种解题思路,一是暴力求解,将矩形一圈圈旋转,从外向内,记录每圈位置并依次旋转;二是先将数组取逆,再互换对角线对称元素,还给出了Python代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode:48. Rotate Image

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]
]

其实就是顺时针旋转一个矩阵(等宽高)。

思路一、暴力求解

摸清楚规律就好:将矩形一圈一圈的旋转,从外向内伸进,添加一个padding,用来记录每一圈的位置。先将top旋转到right,再将right旋转到bottom,然后将bottom旋转到left,最后将left旋转到top

Python 代码实现

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        padding = 0
        paddingEnd = 0
        l = len(matrix)
        if l%2 == 0:
            paddingEnd = (int)(l/2)
        else:
            paddingEnd = (int)((l-1)/2)
        
        for padding in range(paddingEnd):
            
            for i in range(padding+1,l-padding):
                # 1. top -> right
                tmpRight = matrix[i][l-padding-1]
                matrix[i][l-padding-1] = matrix[padding][i]
                
                # 2. right -> bottom
                tmpBottom = matrix[l-padding-1][l-1-i]
                matrix[l-padding-1][l-1-i] = tmpRight
                
                # 3. bottom -> left
                tmpLeft = matrix[l-1-i][padding]
                matrix[l-1-i][padding] = tmpBottom
  
                # 4. left -> top
                matrix[padding][i]=tmpLeft
        
        print(matrix)
思路二

Discuss中的一种方法:先将数组取逆,再将对角线对称的两个元素互换。也可以得到正确结果。

class Solution:
    # @param matrix, a list of lists of integers
    # @return a list of lists of integers
    def rotate(self, matrix):
        matrix.reverse()
        for i in range(len(matrix)):
            for j in range(i):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

THE END.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值