I am trying to implement a recursive search for an arbitrary path (not necessarily a cycle) traversing all graph vertices using Python. Here's my code:
def hamilton(G, size, pt, path=[]):
if pt not in set(path):
path.append(pt)
if len(path)==size:
return path
for pt_next in G[pt]:
res_path = [i for i in path]
hamilton (G, size, pt_next, res_path)
Here, pt
is the starting point and path
is the list of all previously traversed vertices not including pt
, empty by default. The problem is, whenever such a path is found, the return statement refers to some inner call of the procedure and therefore the program does not terminate or return the path.
For example, take G = {1:[2,3,4], 2:[1,3,4], 3:[1,2,4], 4:[1,2,3]}
(i.e. the complete 4-graph) and run hamilton(G,4,1,[])
. It returns None
, but if you print the path instead of returning it as a value, you'll see that it actually finds all six paths starting at 1.
If I tell the program to print the path together with the return statement, it eventually prints all such paths and hence runs much longer than needed.
How can I fix the code so that it would terminate the execution after the first suitable path is found?