看了其他人的代码才看懂
本来想创建矩阵用 zeros,但不能 import numpy
改用 ls = [0,0,0,0], mat.append(ls)得到矩阵,但这样每行都会同时更改数据,因为是引用,链接详见 于是改用 mat.append([0]*n) 链接详见
边界设置为 n-1 而不是 n,方便 range() 设置区间

n = int(input())
mat = []
for i in range(n):
    mat.append([0]*n)
count = 1
h,w = 0,n-1
while h < w:
    for i in range(h,w):
        mat[h][i] = count
        count += 1
    for i in range(h,w):
        mat[i][w] = count
        count += 1
    for i in range(w,h,-1):
        mat[w][i] = count
        count += 1
    for i in range(w,h,-1):
        mat[i][h] = count
        count += 1
    h += 1
    w -= 1
if h == w:
    mat[h][w] = count
for i in range(n):
    for j in range(n):
        print(mat[i][j], end=(' '))
    print()