来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
给定一个包含 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]
解题思路:看到这道题的第一个想法是向剥洋葱一样,从最外层向里面一层一层的获取数据,直到将全部的数据都加入到列表中,AC代码如下:
class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: length = len(matrix) height = len(matrix[0]) ans = [] if not matrix: return ans down = length - 1 up = 0 left = 0 right = height - 1 i = 0 j = 0 while len(ans) < height * length: # 向右遍历 while j <= right and len(ans) < height * length: ans.append(matrix[i][j]) j += 1 up += 1 # 向右遍历时取到了最后一个元素 j -= 1 # 向下遍历 while i < down and len(ans) < height * length: i += 1 ans.append(matrix[i][j]) right -= 1 # 向左遍历 while j > left and len(ans) < height * length: j -= 1 ans.append(matrix[i][j]) down -= 1 # 向上遍历 while i > up and len(ans) < height * length: i -= 1 ans.append(matrix[i][j]) # 一圈遍历结束,向右移动一位 j += 1 left += 1 return ans