给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

输入: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]
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
columns, rows = len(matrix), len(matrix[0]) # 计算矩阵的长度很宽度
# top, bottom, left, right 分别表示矩阵的列的最小索引值和列的最大索引值,行的最小索引值和行的最大索引值的
top, bottom, left, right = 0, columns-1, 0, rows - 1
result_list = list()
while right >= left and bottom >= top:
for i in range(top, right+1):
result_list.append(matrix[top][i]) # 按顺时针把顶层元素添加到list中
for j in range(top+1, bottom+1):
result_list.append(matrix[j][right]) # 按顺时针把最右边的元素添加到list中
if right > left and bottom > left:
for i in range(right-1, left-1, -1):
result_list.append(matrix[bottom][i]) # 按顺时针把底层元素添加到list中
for j in range(bottom-1, top, -1):
result_list.append(matrix[j][left]) # 按顺时针把最左侧的元素添加到list中
# 当外层遍历结束 分别对四边的做相应的调整
top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1
return result_list

该篇博客详细介绍了如何实现一个Python类方法,用于按照顺时针螺旋顺序遍历并返回给定矩阵的所有元素。示例展示了对于不同大小的矩阵,如3x3和4x4,该算法如何正确地输出螺旋顺序的元素列表。
585

被折叠的 条评论
为什么被折叠?



