输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
解决这个问题的关键在于先形成清晰的思路,并把复杂的问题分解成若干个简单的问题。
class Solution:
def __init__(self):
self.value = None
def print_matrix(self, matrix):
if not matrix:
return matrix
rows, cols = len(matrix), len(matrix[0])
start = 0
while cols > start*2 and rows > start*2:
self.print_matrix_in_circle(matrix, rows, cols, start)
start += 1
return self.value
def print_matrix_in_circle(self, matrix, rows, cols, start):
i_end, j_end = cols-1-start, rows-1-start
if self.value is None:
self.value = []
for i in range(start, i_end+1):
self.value.append(matrix[start][i])
if start < j_end:
for j in range(start+1, j_end+1):
self.value.append(matrix[j][i_end])
if start < i_end and start < j_end:
for i in range(i_end-1, start-1, -1):
self.value.append(matrix[j_end][i])
if start < i_end and start < j_end-1:
for j in range(j_end-1, start, -1):
self.value.append(matrix[j][start])
st = Solution()
matrix = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
print(st.print_matrix(matrix))
(最近更新:2019年07月24日)