LeetCode 48+54.旋转图像+螺旋矩阵

一、问题

48、矩阵顺时针旋转90度

题目链接icon-default.png?t=N7T8https://leetcode.cn/problems/rotate-image/solutions/2489887/yuan-di-xuan-zhuan-pythonyi-xing-dai-ma-d0tez

54、给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

题目链接icon-default.png?t=N7T8https://leetcode.cn/problems/spiral-matrix/description/

二、旋转矩阵的方法

        利用字典类型zip,list(zip(*maxtric)) [ :  : -1] 使得矩阵逆时针旋转90度。

顺时针90度:

(1)注意是 matric [ : ]

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        matrix[:]=matrix[::-1]
        matrix[:]=list(zip(*matrix))

   (2)

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        matrix[:] = [row[::-1] for row in zip(*matrix)]

         其中,zip(*maxtric)是把列分别组在一起,list()可以把列组变成行组,现在最左列编程第一行,【::-1】可以使原本的最右列变成第一行。

54、

class Solution:

    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:

        result = []

        while matrix:

            result += matrix.pop(0)  # 取矩阵第一行并删除

            matrix = list(zip(*matrix))[::-1]  # 旋转矩阵

        return result

三、遍历的方法

        不如上面的方法,短小精悍

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix or not matrix[0]:
            return list()
        
        rows, columns = len(matrix), len(matrix[0])
        order = list()
        left, right, top, bottom = 0, columns - 1, 0, rows - 1
        while left <= right and top <= bottom:
            for column in range(left, right + 1):
                order.append(matrix[top][column])
            for row in range(top + 1, bottom + 1):
                order.append(matrix[row][right])
            if left < right and top < bottom:
                for column in range(right - 1, left, -1):
                    order.append(matrix[bottom][column])
                for row in range(bottom, top, -1):
                    order.append(matrix[row][left])
            left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
        return order

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值