给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
延续 59螺旋矩阵II 的思路,依次按照螺旋的顺序添加数字到空列表array中
需要注意的是,与59不同,该输入列表非n*n的,所以需要计算列表的行数和列数,列表的行直接用len()可得出,列数为len(matric[0]),因为此列表的维度为2。
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
row = len(matrix)
col = len(matrix[0])
left, right, top, bottom = 0, col - 1, 0, row - 1
target = row * col
array = []
count = 1
while count <= target:
for i in range(left, right + 1): #从左到右
if count > target:
break
array.append(matrix[top][i])
count += 1
top += 1
for i in range(top, bottom + 1): #从上到下
if count > target:
break
array.append(matrix[i][right])
count += 1
right -= 1
for i in range(right, left - 1, -1): #从右到左
if count > target:
break
array.append(matrix[bottom][i])
count += 1
bottom -= 1
for i in range(bottom, top - 1, -1): #从下到上
if count > target:
break
array.append(matrix[i][left])
count += 1
left += 1
return array