螺旋数组即为从外圈至内圈排列的一组数据
[[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.]
[ 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 15.]
[ 51. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 65. 16.]
[ 50. 95. 132. 133. 134. 135. 136. 137. 138. 139. 140. 107. 66. 17.]
[ 49. 94. 131. 160. 161. 162. 163. 164. 165. 166. 141. 108. 67. 18.]
[ 48. 93. 130. 159. 180. 181. 182. 183. 184. 167. 142. 109. 68. 19.]
[ 47. 92. 129. 158. 179. 192. 193. 194. 185. 168. 143. 110. 69. 20.]
[ 46. 91. 128. 157. 178. 191. 196. 195. 186. 169. 144. 111. 70. 21.]
[ 45. 90. 127. 156. 177. 190. 189. 188. 187. 170. 145. 112. 71. 22.]
[ 44. 89. 126. 155. 176. 175. 174. 173. 172. 171. 146. 113. 72. 23.]
[ 43. 88. 125. 154. 153. 152. 151. 150. 149. 148. 147. 114. 73. 24.]
[ 42. 87. 124. 123. 122. 121. 120. 119. 118. 117. 116. 115. 74. 25.]
[ 41. 86. 85. 84. 83. 82. 81. 80. 79. 78. 77. 76. 75. 26.]
[ 40. 39. 38. 37. 36. 35. 34. 33. 32. 31. 30. 29. 28. 27.]
如果都定义为坐标,其有如下特点:
1、每圈数据个数相对固定,如为NN的数组,最外圈的数据个数为4(N-1)个
2、在其内部,四组边的内的顺序固定,上面的边X不变,Y增加
右面的边Y不变,X增加
下面的边X不变,Y减少
左面的边Y不变,X减少
故此,编写python如下:
pdb请忽略,为中断调试的应用,numpy为数组
#螺旋数组
#成功组成
import numpy as np
import pdb
n=14
a=np.zeros((n,n))
for num in range(1,n**2+1):
number=num
flags=True
cirx=0
ciry=0
cir=1 #求数字在几层内
x=0
y=0
while flags:
if cir==(int(n)+1)/2:
flags=False
cirx=1
ciry=1
x=cir
y=cir
break
if number>4*(n+1-2*cir): #每层的数字个数为4*n-1)
number=number-4*(int(n)+1-2*cir)
cir+=1
else:
#print(number,cirx,ciry)
cirx=int(number/(n+1-2*cir))+1
ciry=number%((n+1-2*cir))
if ciry==0:
cirx-=1
ciry=(n+1-2*cir)
if cirx==1:
x=cir
y=cir+ciry-1
if cirx==2:
y=n-cir+1
x=cir+ciry-1
if cirx==3:
x=n-cir+1
y=n-cir-ciry+2
if cirx==4:
y=cir
x=n-cir-ciry+2
break
a[x-1,y-1]=num
print(a)
#pdb.set_trace() #断点测试
原本想编译中,不能支持偶数行列的数组,运行后发现没有问题,也支持。