That's essentially a pathfinder/search.
Assume that isConnected(a,b) returns if the two nodes are connected
(I am writing the code in Lua, it shouldn't be hard to translate)
function search(list)
local i = 0
while i < 10000 do
i = i + 1
if isConnected(i,list[#list]) then
--This expression refers to the last member
search(list ++ i)
--Although not technically a proper operator, ++ adds the element to the end of the list
end
end
submit_list(list)
end
submit_list
is a function which takes lists, and checks them. It finds the longest submitted list that contains no duplicates. That list will be the solution to your problem.
Oh, one other thing; my code doesn't account for something. In the event that the list contains duplicates nodes, that function should terminate so that it doesn't recurse forever.