欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實(shí)現(xiàn)螺旋矩陣的填充算法示例

 更新時(shí)間:2017年12月28日 08:59:14   作者:afanty_mo  
這篇文章主要介紹了Python實(shí)現(xiàn)螺旋矩陣的填充算法,結(jié)合實(shí)例形式分析了Python實(shí)現(xiàn)螺旋矩陣的相關(guān)循環(huán)、遍歷、判斷、運(yùn)算等操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Python實(shí)現(xiàn)螺旋矩陣的填充算法。分享給大家供大家參考,具體如下:

afanty的分析:

關(guān)于矩陣(二維數(shù)組)填充問題自己動(dòng)手推推,分析下兩個(gè)下表的移動(dòng)規(guī)律就很容易咯。

對(duì)于螺旋矩陣,不管它是什么鬼,反正就是依次向右、向下、向右、向上移動(dòng)。

向右移動(dòng):橫坐標(biāo)不變,縱坐標(biāo)加1
向下移動(dòng):縱坐標(biāo)不變,橫坐標(biāo)加1
向右移動(dòng):橫坐標(biāo)不變,縱坐標(biāo)減1
向上移動(dòng):縱坐標(biāo)不變,橫坐標(biāo)減1

代碼實(shí)現(xiàn):

#coding=utf-8
import numpy
'''''
Author: afanty
Date:  2016/6/23
'''
def helixMatrix(n):
  '''''實(shí)現(xiàn)n維螺旋矩陣的填充
  :param n:維數(shù)
  :return:螺旋矩陣
  '''
  if not isinstance(n, int) or n <= 0:
    raise ValueError('請(qǐng)輸入合適的維數(shù)')
  matrix = numpy.zeros((n, n))
  left_top = 0
  right_buttom = n - 1
  number = 1
  while left_top < right_buttom:
    # 向右移動(dòng),橫坐標(biāo)不變,縱坐標(biāo)+1,number+1
    i = left_top
    while i < right_buttom:
      matrix[left_top][i] = number
      i += 1
      number += 1
    # while
    # 向下移動(dòng),縱坐標(biāo)不變,橫坐標(biāo)+1,number+1
    i = left_top
    while i < right_buttom:
      matrix[i][right_buttom] = number
      i += 1
      number += 1
    #while
    # 向左移動(dòng),橫坐標(biāo)不變,縱坐標(biāo)-1,number+1
    i = right_buttom
    while i > left_top:
      matrix[right_buttom][i] = number
      i -= 1
      number += 1
    # while
    # 向上移動(dòng),縱坐標(biāo)不變,橫坐標(biāo)-1,number+1
    i = right_buttom
    while i > left_top:
      matrix[i][left_top] = number
      i -= 1
      number += 1
    # while
    left_top += 1
    right_buttom -= 1
  # while
  if n % 2 != 0:
    matrix[n / 2][n / 2] = n * n
  return matrix
# end
print("腳本之家測(cè)試結(jié)果:")
print helixMatrix(5)

運(yùn)行結(jié)果:

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論