Leetcode_med 54. 螺旋矩阵

描述

给定一个包含 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]

Python

在这里插入图片描述

利用生成器不断返回元素,添加到list中

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        def generating(r1,c1,r2,c2):
            for c in range(c1,c2+1):
                yield r1,c
            for r in range(r1+1,r2+1):
                yield r,c2
            if r2>r1 and c2>c1:
                for c in range(c2-1,c1,-1):
                    yield r2,c
                for r in range(r2,r1,-1):
                    yield r,c1
        
        if not matrix: return []
        ans = []
        r1,c1 = 0,0
        r2,c2 = len(matrix)-1,len(matrix[0])-1
        while c1<=c2 and r1<=r2:
            for r,c in generating(r1,c1,r2,c2):
                ans.append(matrix[r][c])
            r1+=1
            c1+=1
            r2-=1
            c2-=1
        return ans

猜你喜欢

转载自blog.csdn.net/weixin_38611497/article/details/88019049