题目描述:
给定一个包含 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]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
def spiralOrder(self, matrix):
result = list()
if not matrix:
return result
m, n = len(matrix), len(matrix[0])
left, up, right, down = 0, 0, n-1, m-1
while left <= right and up <= down:
for i in range(left, right+1):
result.append(matrix[up][i])
for j in range(up+1, down+1):
result.append(matrix[j][right])
if left < right and up < down:
for i in range(right-1, left, -1):
result.append(matrix[down][i])
for j in range(down,up, -1):
result.append(matrix[j][left])
left += 1
up += 1
right -= 1
down -= 1
return result