|
发表于 2019-12-23 20:31:03
|
显示全部楼层
def func291_2(n):
if n==0:return []
ret=[[ 0 for _ in range(n)] for x in range(n)]
index=1
fx=[(0,1),(1,0),(0,-1),(-1,0)]#定义向右,下,左,向上四个方向坐标的变化
direct=0
i=j=0#从左上角填起
while index<=n**2:#生成1到n^2
ret[i][j] = index
#边界检查
if direct==0 and (j==n-1 or ret[i][j+1]!=0):
direct=1
elif direct==1 and (i==n-1 or ret[i+1][j]!=0):
direct=2
elif direct==2 and (j==0 or ret[i][j-1]!=0 ):
direct=3
elif direct==3 and (i==0 or ret[i-1][j]!=0):
direct=0
x,y=fx[direct]
i+=x
j+=y
index+=1
return ret |
|