#step1:初始化定义一个转置矩阵
matrix = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
#step2:统计相关指标及初始化存储列表
rows = len(matrix)
cols = len(matrix[0])
left = 0
right = cols - 1
top = 0
bottom = rows - 1
result = []
#step3:循环遍历,顺时针读取存储矩阵元素
while left <= right and top <= right:
#行-从左到右(left,right)
for col in range(left,right+1):
result.append(matrix[top][col])
#列-从上到下(top+1,bottom)
for row in range(top+1,bottom+1):
result.append(matrix[row][right])
#若行与列不等则继续以下遍历
if left < right and top < bottom:
#行-从右到左(right-1,left+1,-1)下角标从右边开始读取
for col in range(right-1,left,-1):
result.append(matrix[bottom][col])
#列-从下到上(bottom,top+1,-1)
for row in range(bottom,top,-1):
result.append(matrix[row][left])
#每循环一次外层循环后更新一次相关变量,进入下一内层循环
left += 1
right -= 1
top += 1
bottom -= 1
print(result)
matrix = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
rows = len(matrix)
cols = len(matrix[0])
left = 0
right = cols -1
top = 0
bottom = rows - 1
result = []
while left <= right and top <= bottom:
for row in range(top,bottom+1):
result.append(matrix[row][left])
for col in range(left+1,right+1):
result.append(matrix[bottom][col])
if left < right and top < bottom:
for row in range(bottom-1,top,-1):
result.append(matrix[row][right])
for col in range(right,left,-1):
result.append(matrix[top][col])
left += 1
right -= 1
top += 1
bottom -= 1
print(result)