每日leetcode-数组-54. 螺旋矩阵

分类:数组-特定顺序遍历二维数组

题目描述:

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

解题思路:每次取第一行,之后把剩下元素逆时针旋转90度,取第一行,再依次循环。

class Solution:
    # matrix类型为二维列表,需要返回列表
    def spiralOrder(self,matrix: List[List[int]]) -> List[int]:
        # write code here
        if not matrix:
            return []
        res = []
        while matrix:
            res.extend(matrix.pop(0))
            matrix = self.TurnM(matrix)
        return res
    
    def TurnM(self, matrix):
        if not matrix:
            return matrix
        res = []
        m = len(matrix[0])
        for i in range(m-1, -1, -1):
            res.append([line[i] for line in matrix])
        return res

自己定义翻转函数TurnM,调用时为self.函数名。

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        while matrix: 
            res += matrix.pop(0)  # 每次提取第一排元素
            matrix = list(zip(*matrix))[::-1]   #[::-1]表示倒序输出  #将剩余的元素进行逆时针旋转九十度
        return res

zip函数:

        """
        1 2 3
        4 5 6
        7 8 9
        matrix.pop(0)

        4 5 6
        7 8 9
        matrix = list(zip(*matrix))[::-1]

        6 9
        5 8
        4 7
        matrix.pop(0)

        5 8
        4 7
        matrix = list(zip(*matrix))[::-1]

        8 7
        5 4
        matrix.pop(0)

        5 4
        matrix = list(zip(*matrix))[::-1]

        4
        5
        matrix.pop(0)

        5
        matrix = list(zip(*matrix))[::-1]

        5
        matrix.pop(0)

        done!
        """
原文地址:https://www.cnblogs.com/LLLLgR/p/14782210.html