leetcode [54] 螺旋矩阵
Contact me:
Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub
给定一个包含 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]
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if len(matrix) == 0 or len(matrix[0]) == 0:
return []
ans = []
left, right, up, down = 0, len(matrix[0]), 0, len(matrix)
while left < right and up < down:
for i in range(left, right):
ans.append(matrix[up][i])
up += 1
for i in range(up, down):
ans.append(matrix[i][right - 1])
right -= 1
if up < down:
for i in range(right - 1, left - 1, -1):
ans.append(matrix[down - 1][i])
down -= 1
if left < right:
for i in range(down - 1, up - 1, -1):
ans.append(matrix[i][left])
left += 1
return ans