题目
给你一个
m
行n
列的矩阵matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
解题
def spiralOrder(matrix):
if not matrix or not matrix[0]:
return []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
result = []
while top <= bottom and left <= right:
# 从左到右
for i in range(left, right + 1):
result.append(matrix[top][i])
top += 1
# 从上到下
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
if top <= bottom:
# 从右到左
for i in range(right, left - 1, -1):
result.append(matrix[bottom][i])
bottom -= 1
if left <= right:
# 从下到上
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1
return result
# 测试
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(spiralOrder(matrix))
标签:right,matrix,螺旋,top,矩阵,len,LeetCode
From: https://blog.csdn.net/weixin_74254879/article/details/141299143