输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
先打印最外面一圈,再打印里面循环。
class Solution:
def printMatrix(self,matrix):
res = []
tr = 0
tc = 0
er = len(matrix) - 1
ec = len(matrix[0]) - 1
while tr <= er and tc <= ec:
self.printma(matrix, tr, tc, er, ec, res)
tr += 1
rc += 1
er -= 1
ec -= 1
return res
def printma(self, matrix, tr, tc, er, ec, res):
if tr == er:
for i in range(tc, ec+1):
res.append(matrix[tr][i])
elif tc == ec:
for i in range(tr, er+1):
res.append(matrix[i][tc])
else:
curr = tr
curc = tc
while curc != ec:
res.append(matrix[tr][curc])
curc += 1
while curr != er:
res.append(matrix[curr][ec])
curr += 1
while curc != tc:
res.append(matrix[er][curc])
curc -= 1
while curr != tr:
res.append(matrix[curr][tc])
curr -= 1