# From recursive to iterative

Given a table nxn and a starting position, it is required to determine a sequence of steps / moves that allow you to go through all the cells once and only once.
The allowed moves are those that move vertically and horizontally by three cells and diagonally by two cells.
I would like to have the iterative form of the following recursive script which finds, for the 5x5 case, 552 different sequences starting from cell (1,1).
The branch () function finds more than 300k for the 6x6 table.
I would also like to see a recursive version that finds only one solution.

``````movs=[CartesianIndex(-3,0),
CartesianIndex(3,0),
CartesianIndex(0,-3),
CartesianIndex(0,3),
CartesianIndex(-2,2),
CartesianIndex(2,-2),
CartesianIndex(-2,-2),
CartesianIndex(2,2),
]

function next(pos,path=[])
p=[pos + m for m in movs if pos+m in tab]
#i=intersect(p,tab)
return setdiff(p,path)
end

paths=[]
function branch(pos, path=[pos])
if length(path)<n*n
vp=next(pos,path)
for i in vp
branch(i,[path;i])
end
else
push!(paths,path)
end
paths
end

n=5
init=CartesianIndex(1,1)
tab=CartesianIndices((1:n,1:n))
branch(init)

julia> init=CartesianIndex(1,1)
CartesianIndex(1, 1)

julia> tab=CartesianIndices((1:n,1:n))
5×5 CartesianIndices{2, Tuple{UnitRange{Int64}, UnitRange{Int64}}}:
CartesianIndex(1, 1)  CartesianIndex(1, 2)  …  CartesianIndex(1, 5)
CartesianIndex(2, 1)  CartesianIndex(2, 2)     CartesianIndex(2, 5)
CartesianIndex(3, 1)  CartesianIndex(3, 2)     CartesianIndex(3, 5)
CartesianIndex(4, 1)  CartesianIndex(4, 2)     CartesianIndex(4, 5)
CartesianIndex(5, 1)  CartesianIndex(5, 2)     CartesianIndex(5, 5)

julia> branch(init)
552-element Vector{Any}:
CartesianIndex{2}[CartesianIndex(1, 1), CartesianIndex(4, 1), CartesianIndex(4, 4), CartesianIndex(1, 4), CartesianIndex(3, 2), CartesianIndex(3, 5), CartesianIndex(5, 3), CartesianIndex(2, 3), CartesianIndex(4, 5), CartesianIndex(1, 5)  …  CartesianIndex(2, 1), CartesianIndex(4, 3), CartesianIndex(1, 3), CartesianIndex(3, 1), CartesianIndex(3, 4), CartesianIndex(5, 2), CartesianIndex(2, 2), CartesianIndex(2, 5), CartesianIndex(5, 5), CartesianIndex(3, 3)]

``````

the solution table of the 5x5 case is generated in tenths of a second.
for that 6x6 it takes several minutes-