版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86679864
原题
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
解法
按行或者按列从matrix中提取数字并将数字放入res中, 每次放入之前要检查matrix是否为空或者行数是否为0.
代码
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
res = []
while matrix:
# add the first row
res += matrix.pop(0)
# add the right-most col
if matrix and matrix[0]:
for row in matrix:
res.append(row.pop())
# add the bottom row from right to left
if matrix:
res += matrix.pop()[::-1]
# add the left-most col from bottom to up
if matrix and matrix[0]:
res += [row.pop(0) for row in matrix][::-1]
return res