题意:螺旋打印二维矩阵html
直接按照螺旋的思想一个个打印出来。python
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return matrix
start_row, end_row = 0, len(matrix) - 1
start_col, end_col = 0, len(matrix[0]) - 1
ans = []
while start_row <= end_row and start_col <= end_col:
# 向右移动
for j in range(start_col, end_col+1):
ans.append(matrix[start_row][j])
start_row += 1
# 向下移动
for i in range(start_row, end_row+1):
ans.append(matrix[i][end_col])
end_col -= 1
# 向左移动
if start_row <= end_row:
for j in range(end_col, start_col-1, -1):
ans.append(matrix[end_row][j])
end_row -= 1
# 向上移动
if start_col <= end_col:
for i in range(end_row, start_row-1, -1):
ans.append(matrix[i][start_col])
start_col += 1
return ans
思想和上面螺旋的思想是一致的,不同的是其用的是数组的弹出的作法来获取元素,可是这有个缺点-数组的弹出可能会致使运行时间的增长。web
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
这种写法很是Pythonic,可是在大的的数组中会很是的耗时,其思想就是每次递归时取第一个子数组,将剩余的子数组进行zip,反转获得的数组再进行递归。数组
class Solution(object):
def spiralOrder(self, matrix):
return matrix and list(matrix.pop(0)) + spiralOrder(list(zip(*matrix))[::-1])