
程序代码:
n = input("请输入矩阵维数:")
n = int(n)
if n > 0:
direction = [[1, 0, -1, 0], [0, -1, 0, 1]] # 方向,下左上右
array = [[0 for i in range(n)] for j in range(n)] # 创建二维数组
row = 0
column = n-1
current_dir = 0
for i in range(n*n):
# print(f"{row},{column},{i+1},{current_dir}")
array[row][column] = i+1
next_row = row + direction[0][current_dir]
next_column = column + direction[1][current_dir]
if next_row >= n or next_column >= n or next_row < 0 or next_column < 0:
current_dir = (current_dir+1) % 4
row += direction[0][current_dir]
column += direction[1][current_dir]
elif array[next_row][next_column] != 0:
current_dir = (current_dir + 1) % 4
row += direction[0][current_dir]
column += direction[1][current_dir]
else:
row = next_row
column = next_column
for i in range(n):
for j in range(n):
print(f"{array[i][j]}\t", end="")
print("\n", end="")