本文实例为大家分享了python实现转圈打印矩阵的具体代码,供大家参考,具体内容如下

#! conding:utf-8
__author__ = "hotpot"
__date__ = "2017/10/28 9:40"


def return_edge(matrix, start_col, end_col, start_row, end_row):
  if start_row == end_row:
    return matrix[start_row][start_col:end_col+1]
  elif end_col ==start_col:
    res = []

    for i in range(start_row,end_row+1):
      res.append(matrix[i][end_col])
    return res
  else:
    res2 =[]
    res3 =[]
    res4=[]
    res1 = matrix[start_row][start_col:end_col+1]
    for i in range(start_row+1,end_row+1):
      res2.append(matrix[i][end_col])
    for i in range(end_col-1,start_col-1,-1):
      res3.append(matrix[end_row][i])
    for i in range(end_row-1,start_row,-1):
      res4.append(matrix[i][start_row])
    res1.extend(res2)
    res1.extend(res3)
    res1.extend(res4)
    return res1
def spiralOrder( matrix):
  if matrix:
    row = len(matrix)-1
    col = len(matrix[0])-1
    start_row = 0
    start_col = 0
    end_row = row
    end_col = col
    res =[]
    while start_col<=end_col and start_row <= end_row:
      res.extend(return_edge(matrix,start_col,end_col , start_row ,end_row))
      start_col+=1
      end_col-=1
      start_row+=1
      end_row-=1
    return res
  else:
    return matrix
if __name__ == '__main__':
  matrix = [[0 for i in range(3) ]for j in range(3)]
  num=1
  for m in range(len(matrix)):
    for n in range(len(matrix[0])):
      matrix[m][n]=num
      num+=1

  print(spiralOrder( matrix))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com