把矩阵想象成若干个圈,可以用一个循环来打印矩阵,每次打印矩阵中的一个圈。
def print_matrix(matrix):
"""
:param matrix: [[]]
"""
rows = len(matrix)
cols = len(matrix[0]) if matrix else 0
start = 0
ret = []
while start * 2 < rows and start * 2 < cols:
print_circle(matrix, start, rows, cols, ret)
start += 1
print ret
def print_circle(matrix, start, rows, cols, ret):
row = rows - start - 1 # 最后一行
col = cols - start - 1
# left->right
for c in range(start, col+1):
ret.append(matrix[start][c])
# top->bottom
'''
终止行号大于起始行号
'''
if start < row:
for r in range(start+1, row+1):
ret.append(matrix[r][col])
# right->left
'''
至少有两行两列
终止行号大于起始行号,并且终止列号大于起始列号
'''
if start < row and start < col:
for c in range(start, col)[::-1]:
ret.append(matrix[row][c])
# bottom->top
'''
至少有三行两列
终止行号至少比起始行号大2,并且终止列号大于起始列号
'''
if start < row-1 and start < col:
for r in range(start+1, row)[::-1]:
ret.append(matrix[r][start])
注意:
在从右向左,以及从下往上打印的时候,遍历的范围是这样的:
range(start, col)[::-1]
range(start+1, row)[::-1]
当start=0,col=3
时,
>>> print(list(range(0,3)[::-1]))
[2, 1, 0]
对应的是:
注意:
取值范围不能写成range(col, start, -1)
>>> print(list(range(3,0,-1)))
[3, 2, 1]
参考:
https://github.com/JushuangQiao/Python-Offer/tree/master/fourth/second