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

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

记录自己的填坑之旅


#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

你可能感兴趣的:(算法,Python,算法,面试题)