题目描述:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
我的思路:
把一个m*n的矩阵旋转输出成一个数组。按照顺时针方向不断将元素弹出,像是剥皮一样。
也可以递归输出,每次输出一圈,之后再对内圈矩阵调用打印函数,但是要注意下边界的条件,比如到最后只剩下一个行,或者一列或者是一个元素。
我的代码:
class Solution:
def spiralOrder(self, matrix):
"""
也可以通过递归来实现。
"""
ret = []
while matrix:
ret += matrix.pop(0)
if matrix and matrix[0]:
for row in matrix:
ret.append(row.pop())
if matrix:
ret += matrix.pop()[::-1]
if matrix and matrix[0]:
for row in matrix[::-1]:
ret.append(row.pop(0))
return ret
Discuss:
Stefan大神的1line python代码,哈哈。评论了有人回复:How can you be so motherfucking good? accept my knees
def spiralOrder(self, matrix):
return matrix and [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1]) # spiralOrder里面的东西相当于逆时针旋转90°
学到:
- 一个列表pop()是会改变元列表,默认输出的是列表尾部的元素。
- 对一个列表[::-1],相当于翻转列表。
- 逆时针旋转90°是
[*zip(*matrix)][::-1]