Python實現螺旋矩陣的填充算法示例
本文實例講述了Python實現螺旋矩陣的填充算法。分享給大家供大家參考,具體如下:
afanty的分析:
關于矩陣(二維數組)填充問題自己動手推推,分析下兩個下表的移動規(guī)律就很容易咯。
對于螺旋矩陣,不管它是什么鬼,反正就是依次向右、向下、向右、向上移動。
向右移動:橫坐標不變,縱坐標加1
向下移動:縱坐標不變,橫坐標加1
向右移動:橫坐標不變,縱坐標減1
向上移動:縱坐標不變,橫坐標減1
代碼實現:
#coding=utf-8
import numpy
'''''
Author: afanty
Date: 2016/6/23
'''
def helixMatrix(n):
'''''實現n維螺旋矩陣的填充
:param n:維數
:return:螺旋矩陣
'''
if not isinstance(n, int) or n <= 0:
raise ValueError('請輸入合適的維數')
matrix = numpy.zeros((n, n))
left_top = 0
right_buttom = n - 1
number = 1
while left_top < right_buttom:
# 向右移動,橫坐標不變,縱坐標+1,number+1
i = left_top
while i < right_buttom:
matrix[left_top][i] = number
i += 1
number += 1
# while
# 向下移動,縱坐標不變,橫坐標+1,number+1
i = left_top
while i < right_buttom:
matrix[i][right_buttom] = number
i += 1
number += 1
#while
# 向左移動,橫坐標不變,縱坐標-1,number+1
i = right_buttom
while i > left_top:
matrix[right_buttom][i] = number
i -= 1
number += 1
# while
# 向上移動,縱坐標不變,橫坐標-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("腳本之家測試結果:")
print helixMatrix(5)
運行結果:

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python加密解密算法與技巧總結》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python中使用第三方庫xlutils來追加寫入Excel文件示例
這篇文章主要介紹了Python中使用第三方庫xlutils來追加寫入Excel文件示例,本文直接給出追加寫入示例和追加效果,需要的朋友可以參考下2015-04-04
解決springboot yml配置 logging.level 報錯問題
今天小編就為大家分享一篇解決springboot yml配置 logging.level 報錯問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
利用rest framework搭建Django API過程解析
這篇文章主要介紹了利用rest framework搭建Django API過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08

