"""
[
[1, 2, 3, 4, 5],
[16, 17, 18, 19, 6],
[15, 24, 25, 20, 7],
[14, 23, 22, 21, 8],
[13, 12, 11, 10, 9]
]
"""
def main(n):
result = [[0] * n for _ in range(n)]
show_num = 1
start_line = 0
row = n - 1
col = n - 1
def matrix(start_line, show_num, row, col):
if row == 0:
if n % 2 != 0:
result[n // 2][n // 2] = n * n
else:
for i in range(start_line, col):
result[start_line][i] = show_num
show_num += 1
for i in range(start_line, row):
result[i][row] = show_num
show_num += 1
for i in range(row, start_line, -1):
result[row][i] = show_num
show_num += 1
for i in range(col, start_line, -1):
result[i][start_line] = show_num
show_num += 1
return matrix(start_line+1, show_num, row-1, col-1)
matrix(start_line, show_num, row, col)
return result
if __name__ == '__main__':
result = main(4)
for i in result:
for x in i:
print(format(x, '3'), end=' ')
print()
"""
result:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
"""
n阶螺旋矩阵
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...