1. 顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
方法一:
def spiralOrder(matrix):
if not matrix:
return []
res = []
rows = len(matrix)
cols = len(matrix[0])
top, bottom = 0, rows - 1
left, right = 0, cols - 1
size = rows * cols
while len(res)!= size:
for i in range(left, right + 1):
res.append(matrix[top][i])
top += 1
if len(res) == size:
break
for i in range(top, bottom + 1):
res.append(matrix[i][right])
right -= 1
if len(res) == size:
break
for i in range(right, left - 1, -1):
res.append(matrix[bottom][i])
bottom -= 1
if len(res) == size:
break
for i in range(bottom, top - 1, -1):
res.append(matrix[i][left])
left += 1
return res
方法二:
def spiralOrder(matrix):
if not matrix:
return []
result = []
while matrix:
result.extend(matrix.pop(0))
if matrix and matrix[0]:
rotated = [list(col) for col in zip(*matrix)]
matrix = rotated[::-1]
return result