参考楼上有限状态机,改了改x,y的顺序,更喜欢顺着坐标系,而不是顺着row和colomn。

n = int(input())
position = [[-1 for _ in range(0,n)]for _ in range(0,n)]
direction = [[1,0],[0,1],[-1,0],[0,-1]]
state = 0
cnt = 0
trace = []
x,y=0,0
for p in range(n**2):
    cnt+=1
    position[x][y]=cnt
    trace.append([x,y])
    x+=direction[state%4][0]
    y+=direction[state%4][1]
    if ([x,y] in trace) or x>=n or x<0 or y <0 or y>=n:
        x-=direction[state%4][0]
        y-=direction[state%4][1]
        state+=1
        x+=direction[state%4][0]
        y+=direction[state%4][1]
for i in range(0,n):
    for j in range(0,n):
        print(position[j][i],end=" ")
    print()