顺时针打印矩阵 牛客网 剑指Offer

mac2022-06-30  110

顺时针打印矩阵 牛客网 剑指Offer

题目描述输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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: #run:33ms memory:5712k def printMatrix(self, matrix): if matrix is None: return None if matrix is []: return [] r = len(matrix) c = len(matrix[0]) lt = [] start = 0 while c > 2 * start and r > 2 * start: endX = c - 1 - start endY = r - 1 - start for i in range(start,endX+1): lt.append(matrix[start][i]) if start < endY: for i in range(start+1,endY+1): lt.append(matrix[i][endX]) if start < endX and start < endY: for i in range(endX-1,start-1,-1): lt.append(matrix[endY][i]) if start < endX and start < endY -1: for i in range(endY-1,start,-1): lt.append(matrix[i][start]) start +=1 return lt

 

转载于:https://www.cnblogs.com/vercont/p/10210348.html

最新回复(0)