1. 程式人生 > >蛇形矩陣 Python3

蛇形矩陣 Python3

數字螺旋矩陣

下邊的程式碼是6階蛇形矩陣的構造和輸出

N = 6
counter=[]
for a in range(N):
    counter.append(N-a)
    counter.append(N-a)
del counter[0]
counter[0]=counter[0]-1
counter.append(1) #把N階蛇形每次要走的步數計算出來存到一個LIST裡,每個方向的最後一個賦值屬於下一個方向的第一步
print(counter)
value = 1
rowID=0
colID=0
multilist = [[0 for col in range(N)] for row in range
(N)] print(multilist) for i in range(len(counter)): for j in range(counter[i]): if(i % 4 == 0): multilist[rowID][colID] = value if(colID != N - 1): colID += 1 if (i % 4 == 1): multilist[rowID][colID] = value if (rowID != N - 1
): rowID += 1 if (i % 4 == 2): multilist[rowID][colID] = value if (colID != 0): colID -= 1 if (i % 4 == 3): multilist[rowID][colID] = value if (rowID != 0): rowID -= 1 value += 1 for e in multilist: print
(e) for e in multilist: for e2 in e: print(e2),
最終執行結果如下圖