Python 生成回旋数矩阵:代码实现及优化
def print_spiral(n): # 创建一个空的n*n的二维列表 spiral = [[0] * n for _ in range(n)]
# 定义四个方向
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
direction_index = 0
row = 0
col = 0
for num in range(1, n * n + 1):
spiral[row][col] = num
# 判断下一个位置是否越界或已经被填充过,如果是则改变方向
next_row = row + directions[direction_index][0]
next_col = col + directions[direction_index][1]
if next_row < 0 or next_row >= n or next_col < 0 or next_col >= n or spiral[next_row][next_col] != 0:
direction_index = (direction_index + 1) % 4
# 更新行和列的值
row += directions[direction_index][0]
col += directions[direction_index][1]
# 打印结果
for row in spiral:
for num in row:
print('{:02d}'.format(num), end=" ")
print()
测试
n = int(input('请输入正方形的行(或列)元素个数n(n>=3,n<=9): ')) print_spiral(n)
原文地址: https://www.cveoy.top/t/topic/pcYm 著作权归作者所有。请勿转载和采集!