看注释解析还是比较简单的,只有4条规则约束
n = int(input())
state = 0
x,y=0,0
position=[[-1 for _ in range(0,n)] for _ in range(0,n)]
trace=[]
cnt = 0
allstate=[[1,-1],[-1,1]]
direction=[[1,0],[0,1]]
# 分别为右上,左下,右,下。
for i in range(0,n**2):
cnt += 1
position[x][y] = cnt
x += allstate[state%2][0]
y += allstate[state%2][1]
#先向右上移动,如果到墙角了,就回退并且向右走一格
if (state%2 == 0 or state == 0) and (x>=n or x<0 or y>=n or y<0):
x -= allstate[state%2][0]
y -= allstate[state%2][1]
state += 1
x += direction[0][0]
y += direction[0][1]
#向右走一格失败则回退并向下走
if(x>=n or x<0 or y>=n or y<0):
x -= direction[0][0]
y -= direction[0][1]
x += direction[1][0]
y += direction[1][1]
#先向右上移动,如果到墙角了,就回退并且向右走一格
if (state%2 != 0 or state == 1) and (x>=n or x<0 or y>=n or y<0):
x -= allstate[state%2][0]
y -= allstate[state%2][1]
state+=1
x += direction[1][0]
y += direction[1][1]
#向下走一格失败则回退并向右走
if(x>=n or x<0 or y>=n or y<0):
x -= direction[1][0]
y -= direction[1][1]
x += direction[0][0]
y += direction[0][1]
for i in range(0,n):
for j in range(0,n):
print(position[j][i],end=" ")
print()