54. 螺旋矩阵
Difficulty: 中等
给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入: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]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
Solution
逐层向里面遍历,考虑转弯太复杂了。
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
res = []
left, top, right, down = 0, 0, len(matrix[0]) - 1, len(matrix) - 1
while left <= right and top <= down:
for i in range(left, right + 1):
res.append(matrix[top][i])
for i in range(top + 1, down + 1):
res.append(matrix[i][right])
if left < right and top < down:
# 考虑1*n和n*1两种特殊情况下的矩阵
for i in range(right - 1, left, -1):
res.append(matrix[down][i])
for i in range(down, top, -1):
res.append(matrix[i][left])
left += 1
top += 1
down -= 1
right -= 1
return res