输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
ps:
0 <= matrix.length <= 1000 <= matrix[i].length <= 100
螺旋打印数组,可以围着打印一圈,注意循环条件
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return list()
rows, columns = len(matrix), len(matrix[0])
order = list()
left, right, top, bottom = 0, columns - 1, 0, rows - 1
while left <= right and top <= bottom:
for column in range(left, right + 1):
order.append(matrix[top][column])
for row in range(top + 1, bottom + 1):
order.append(matrix[row][right])
if left < right and top < bottom:
for column in range(right - 1, left, -1):
order.append(matrix[bottom][column])
for row in range(bottom, top, -1):
order.append(matrix[row][left])
left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
return order
本文详细解析了如何按顺时针螺旋顺序打印矩阵中的元素,适用于0到100大小的矩阵。通过定义边界和循环条件,实现了从外向内的螺旋打印过程。
&spm=1001.2101.3001.5002&articleId=106569146&d=1&t=3&u=63dfa09bd0764a5bb8cb0b0ed976918f)
592

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



