https://leetcode-cn.com/problems/spiral-matrix/
难度:中等
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
示例 2: 输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 输出:[1,2,3,4,8,12,11,10,9,5,6,7]
分别定位top bottom left right 四个点,即可完成动态获取
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
left = top = 0
right = len(matrix[0])
bottom = len(matrix)
ret = []
while left < right and top < bottom:
for i in range(left, right):
ret.append(matrix[top][i])
top += 1
for i in range(top, bottom):
ret.append(matrix[i][right - 1])
right -= 1
if left < right and top < bottom:
for i in range(right - 1, left - 1, -1):
ret.append(matrix[bottom - 1][i])
bottom -= 1
for i in range(bottom - 1, top - 1, -1):
ret.append(matrix[i][left])
left += 1
return ret欢迎关注我的公众号: 清风Python
我的个人博客:https://qingfengpython.cn