输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
思路:定义四个变量,表示左上和右下的打印范围,一次旋转打印结束后,往对角分别前进和后退一个单位。
def printMatrix(self, matrix):
# write code here
rows=len(matrix)
cols=len(matrix[0])
result=[]
if rows==0 and cols==0:
return result
left,right,top,bottom = 0,cols-1,0,rows-1
while left<=right and top<=bottom:
for i in range(left,right+1):
result.append(matrix[top][i]) #上面一行
for i in range(top+1,bottom+1):
result.append(matrix[i][right]) #右边一行
if top!=bottom:
for i in range(right-1,left-1,-1):
result.append(matrix[bottom][i]) #下面一行
if left!=right:
for i in range(bottom-1,top,-1):
result.append(matrix[i][left]) #左边一行
left+=1
right-=1
top+=1
bottom-=1
return result
本文详细解析了如何通过定义四个变量表示打印范围,实现从外向里以顺时针顺序打印矩阵元素的算法。该算法适用于任何大小的矩阵,通过不断调整边界值,实现了对矩阵的逐层遍历。
427

被折叠的 条评论
为什么被折叠?



