[54][中等] 螺旋矩阵
题目描述
54. 螺旋矩阵 剑指 Offer 29. 顺时针打印矩阵 59. 螺旋矩阵 II
给定一个包含 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]
解题思路
Spiral Matrix II (模拟法,设定边界,代码简短清晰)
上面这种思路, 边界清晰. 外层循环每次走一圈, 循环内部, 依次循环顶部, 右部, 底部, 左部, 整个过程判断是否收集了足够数量的元素, 收集到足够元素后停止.
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if len(matrix) == 0:
return []
n, m = len(matrix), len(matrix[0])
num_total, res = n * m, []
left, right, top, bottom = 0, m - 1, 0, n - 1
while len(res) < num_total:
if len(res) < num_total:
for j in range(left, right + 1):
res.append(matrix[top][j])
top += 1
if len(res) < num_total:
for i in range(top, bottom + 1):
res.append(matrix[i][right])
right -= 1
if len(res) < num_total:
for j in range(right, left - 1, -1):
res.append(matrix[bottom][j])
bottom -= 1
if len(res) < num_total:
for i in range(bottom, top - 1, -1):
res.append(matrix[i][left])
left += 1
return res
最后更新于
这有帮助吗?