
以前写过2个关于螺旋矩阵的帖子,分别是matlab方法与python的模拟填空法,都是从左上角开始生长.在checkio的一道题中需要生成从中心开始螺旋生长的矩阵.方法还是类似于模拟填空法.这次需要判断的不再是到达边界转向,而是根据目前的方向,判断下一方向的位置是否为空,如果为空就转向继续写,与人工填写完全一致.需要注意的是中心位置的选取根据size的奇偶性有一些差别.
代码与测试
##9 2 3
##8 1 4
##7 6 5
def spiralmat(n):
# create a spiral matrix starting from centre
c = 1 # current index
d = 0 # initial direction: 1-up,2-right,3-down,4-left
# start from centre
if n%2==0:
i,j = n/2,n/2-1
else:
i,j = n/2,n/2
mat = [[0]*n for x in range(n)]
while c<=n*n:
mat[i][j] = c
c += 1
if d==0: # start
i -= 1
d = 1
elif d==1: # up
if mat[i][j+1]==0:
j += 1
d = 2
else:
i -= 1
elif d==2: # right
if mat[i+1][j]==0:
i += 1
d = 3
else:
j += 1
elif d==3: # down
if mat[i][j-1]==0:
j -= 1
d = 4
else:
i += 1
elif d==4: # left
if mat[i-1][j]==0:
i -= 1
d = 1
else:
j -= 1
return mat
def printmat(mat):
for row in mat:
for col in row:
print '{0:2d}'.format(col),
print
# test
n = 5
printmat(spiralmat(n))
print
n = 6
printmat(spiralmat(n))测试结果如下:
>>> 25 10 11 12 13 24 9 2 3 14 23 8 1 4 15 22 7 6 5 16 21 20 19 18 17 26 27 28 29 30 31 25 10 11 12 13 32 24 9 2 3 14 33 23 8 1 4 15 34 22 7 6 5 16 35 21 20 19 18 17 36
No comments :
Post a Comment