Can anyone suggest an algorithm for this problem.
Given an undirected unweighted cyclic graph, and a given start and end node in that graph, I'd like to determine if there is exactly one valid path from start to end visiting all nodes (i.e. a Hamiltonian path, not a cycle).
It's NP-hard, but my N is relatively small (up to 30 nodes or so) and each node's connectivity is typically very small (no more than 4-5, often 2 or 3, typically local links [i.e. they correspond to locations in 2d connected to near neighbours]), so I'm confident it is feasible.
Published algorithms are typically for cycles, for finding a single solution, and for unknown start and end points. I'm curious if anyone can suggest something more fitting, or if you have any intuition on an approach.
Best Answer
If the problem is small enough, a totally naive approach works well. We want to generate all pinned hamiltonian paths connecting two nodes a and b in a given graph. For this, we just generate all valid paths originating from a and filter out those that are not hamiltonian or that do not end in b.
The following code snippet is an implementation of this idea in OCaml. On my machine it can find all pinned hamiltonian path in a complete graph of size 9 (there is (9-2)! = 5040 such paths, they are all the permutations of 7 non-pinned nodes), but the program cannot handle the case of size 10. This should give you an idea of the complexity of the operation, but as you see, I could not be less naive when implementing this.
There are three examples of graphs defined, the first one is:
the second one is a complete graph without loops (edges having the same start and end points) and the third one is the disjoint union of the two. With these definitions we can experiment a bit in the toplevel: