Python中实现贪吃蛇矩阵(螺旋矩阵)
废话不多说,直接上代码
def snake(n):
arr = [[0] * n for i in range(n)]
flag = 1
for k in range(int(n/2)):
for up in range(k, n-1-k):
arr[k][up] = flag
flag += 1
for right in range(k, n-1-k):
arr[right][n-1-k] = flag
flag += 1
for down in range(n-1-k, k, -1):
arr[n-1-k][down] = flag
flag += 1
for left in range(n-1-k, k, -1):
arr[left][k] = flag
flag += 1
if n%2 != 0:
arr[int((n-1)/2)][int((n-1)/2)] = flag
return arr
snake(5)
[[1, 2, 3, 4, 5],
[16, 17, 18, 19, 6],
[15, 24, 25, 20, 7],
[14, 23, 22, 21, 8],
[13, 12, 11, 10, 9]]