OFFSET
1,2
EXAMPLE
Triangular spiral (A214230) begins:
.
56
| \
55 57
| \
54 29 58
| | \ \
53 28 30 59
| | \ \
52 27 11 31 60
| | | \ \ \
51 26 10 12 32 61
| | | \ \ \
50 25 9 2 13 33 62
| | | | \ \ \ \
49 24 8 1 3 14 34 63
| | | \ \ \ \
48 23 7---6---5---4 15 35 64
| | \ \ \
47 22--21--20--19--18--17--16 36 65
| \ \
46--45--44--43--42--41--40--39--38--37 66
\
78--77--76--75--74--73--72--71--70--69--68--67
.
Square spiral (defining order in which elements are fetched) begins:
.
49 26--27--28--29--30--31
| | |
48 25 10--11--12--13 32
| | | | |
47 24 9 2---3 14 33
| | | | | | |
46 23 8 1 4 15 34
| | | | | |
45 22 7---6---5 16 35
| | | |
44 21--20--19--18--17 36
| |
43--42--41--40--39--38--37
PROG
(Python)
SIZE = 33 # must be 4k+1
grid = [0] * (SIZE*SIZE)
posX = posY = SIZE//2
grid[posY*SIZE+posX]=1
n = 2
def walk(stepX, stepY, chkX, chkY):
global posX, posY, n
while 1:
posX+=stepX
posY+=stepY
grid[posY*SIZE+posX]=n
n+=1
if grid[(posY+chkY)*SIZE+posX+chkX]==0:
return
while 1:
walk(0, -1, 1, 1) # up
walk( 1, 1, -1, 0) # right-down
if posX==SIZE-1:
break
walk(-1, 0, 0, -1) # left
import sys
grid2 = [0] * (SIZE*SIZE)
posX = posY = SIZE//2
grid2[posY*SIZE+posX]=1
def walk2(stepX, stepY, chkX, chkY):
global posX, posY
while 1:
a = grid[posY*SIZE+posX]
if a==0:
sys.exit(1)
print a,
posX+=stepX
posY+=stepY
grid2[posY*SIZE+posX]=1
if grid2[(posY+chkY)*SIZE+posX+chkX]==0:
return
while posX:
walk2(0, -1, 1, 0) # up
walk2(1, 0, 0, 1) # right
walk2(0, 1, -1, 0) # down
walk2(-1, 0, 0, -1) # left
CROSSREFS
KEYWORD
nonn,easy
AUTHOR
Alex Ratushnyak, Sep 23 2012
STATUS
approved