二维矩阵循环打印内容【算法】

二维矩阵循环打印内容【算法】

记录自己的填坑之旅


#conding:utf-8

arry =  [
    [1, 2, 3, 4, 5, 6],
    [16, 17, 18, 19, 20, 7],
    [15, 24, 23, 22, 21,8],
    [14, 13, 12, 11, 10, 9]
]


def double_list_screw(source_list):
    new_list = []
    #每层有四种遍历情况,上下左右,分别处理输出 
    h_len = len(source_list) 
    if h_len > 0:
      w_len = len(source_list[0])
    else: 
      w_len = 0 
    x_start,y_start,x_end,y_end = 0,0,w_len-1,h_len-1 
    while x_start <= x_end and y_start <= y_end:
        for i in range(x_start,x_end + 1):
          # print(source_list[y_start][i])
          new_list.append(source_list[y_start][i])
          # y_start = y_start + 1
          # print(y_start,2222)
          if y_start > y_end:
            break
        y_start = y_start + 1
        for i in range(y_start,y_end+1): 
          # print(source_list[i][x_end])
          new_list.append(source_list[i][x_end])
          # x_end = x_end - 1
          # print(x_end)
        x_end = x_end - 1
        for i in range(x_end,x_start-1,-1): 
          # print(source_list[y_end][i])
          new_list.append(source_list[y_end][i])
          # y_end = y_end - 1
          # print(y_end)
        y_end = y_end - 1
        if x_start>x_end:
          break 
        for i in range(y_end,y_start-1,-1): 
          # print(source_list[i][x_start])
          new_list.append(source_list[i][x_start])
          # x_start = x_start + 1
          # print(x_start)
        x_start = x_start + 1
    print(new_list)

if __name__ == "__main__":
  double_list_screw(arry)

  • 其中遇到的问题:除了判断while循环的x,y起始坐标是否越界,还需要判断一种特殊情况:最后一圈只剩一行或者一列,因此在while循环内部加两个判断语句。
if y_start > y_end : 
	break
if x_start > x_end:
	break
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值