本文實(shí)例講述了Python實(shí)現(xiàn)螺旋矩陣的填充算法。分享給大家供大家參考,具體如下:
afanty的分析:
關(guān)于矩陣(二維數(shù)組)填充問(wèn)題自己動(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-8import numpy'''''Author: afantyDate: 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# endprint("武林站長(zhǎng)站測(cè)試結(jié)果:")print helixMatrix(5)運(yùn)行結(jié)果:

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門(mén)與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注