54. 螺旋矩阵
程序员文章站
2022-07-12 09:48:23
...
给定一个包含 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:
return []
up = 0
down = len(matrix)-1
left = 0
right = len(matrix[0])-1
res = list()
while up <= down and left <= right:
# 上
res.extend(matrix[up][left:right+1])
up += 1
if up > down:
break
# 右
# i = up
# while i <= down:
# res.append(matrix[i][right])
# i += 1
res.extend([matrix[i][right] for i in range(up, down + 1)]) # 替代上面的循环
right -= 1
if left > right:
break
# 下
temp = matrix[down][left:right+1]
res.extend(temp[::-1]) # 逆序
down -= 1
if up > down:
break
# 左
# i = down
# while i >= up:
# res.append(matrix[i][left])
# i -= 1
res.extend([matrix[i][left] for i in range(down, up-1, -1)]) # 替代上面的循环,但执行用时似乎比上面的长
left += 1
if left > right:
break
return res
if __name__=='__main__':
s = Solution()
matrix = \
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
print(s.spiralOrder(matrix))