【Python螺旋输出所有矩阵元素】| 顺时针&逆时针

  • 顺时针实现

 #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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值