效果:
分析
如圖沪斟,確定轉(zhuǎn)彎線士飒,通過判斷轉(zhuǎn)彎線,改變行列讲岁,從而確定數(shù)字的放置位置我擂。
實(shí)現(xiàn)代碼如下:
size = int(input("請(qǐng)輸入行數(shù):"))
lst = [[0] * size]
# print(lst)
for i in range(size - 1):
lst += [[0] * size]
# 定義繞圈方向:0->向下衬以,1->向右,2->向上校摩,3->向左
orient = 0
row = 0
col = 0
for i in range(1, size * size + 1):
# print(row, col,i)
lst[row][col] = i
#判斷拐點(diǎn)
if row + col == size - 1: # 左下-右上對(duì)角線
if row > col:
orient = 1
else:
orient = 3
elif row == col and row >= size / 2:# 中心點(diǎn)到右上角的對(duì)角線
orient = 2
elif row == col - 1 and row <= size / 2 and col <=size/2:#上半部分轉(zhuǎn)著線
orient = 0
#根據(jù)拐點(diǎn)改變行列
if orient == 0:
row += 1
elif orient == 1:
col += 1
elif orient == 2:
row -= 1
elif orient == 3:
col -= 1
#打印存儲(chǔ)好數(shù)據(jù)的二維列表
for i in range(size):
for j in range(size):
print('%02d' % lst[i][j], end=" ")
print("")