题目:
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
别人的trick,递归+zip函数
1 class Solution: 2 def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 3 return matrix and list(matrix.pop(0)) + self.spiralOrder(list(zip(*matrix))[::-1])
matrix = [[1,2,3],[4,5,6],[7,8,9]] --> [1,2,3,6,9,8,7,4,5]
-------------------------------------------------------------------------------
┊ list(matrix.pop(0))=[1,2,3] list(zip(*matrix))=[(4,7),(5,8),(6,9)][::-1]
┊ matrix = [(6,9),(5,8),(4,7)]
┊ ---------------------------------------------------------------------------
┊ ┊ list(matrix.pop(0))=[6,9] list(zip(*matrix))=[(5,4),(8,7)][::-1]
┊ ┊ matrix = [(8,7),(5,4)]
┊ ┊ -----------------------------------------------------------------------
┊ ┊ ┊ list(matrix.pop(0))=[8,7] list(zip(*matrix))=[(5,),(4,)][::-1]
┊ ┊ ┊ matrix = [(4,),(5,)]
┊ ┊ ┊ -------------------------------------------------------------------
┊ ┊ ┊ ┊ list(matrix).pop(0))=[4] list(zip(*matrix))=[(5,)][::-1]
┊ ┊ ┊ ┊ matrix = [(5,)]
┊ ┊ ┊ ┊ ---------------------------------------------------------------
┊ ┊ ┊ ┊ ┊ list(matrix).pop(0))=[5] list(zip(*matrix))=[]
┊ ┊ ┊ ┊ ┊ matrix = []
┊ ┊ ┊ ┊ ┊ -----------------------------------------------------------
┊ ┊ ┊ ┊ ┊ ┊ [] and self.spiralOrder(list(zip(*matrix))[::-1])
┊ ┊ ┊ ┊ ┊ ┊ Returns the first null value without subsequent operations
-------------------------------------------------------------------------------