Skip to content Skip to sidebar Skip to footer

Build All Hamiltonian Paths From An Edge List

I'm having trouble finding a way to build a tree path from a list of related tuples? I only want a list of every path where each node is visited once, aka hamiltonian path. I keep

Solution 1:

OK, I was having so much trouble because of the data structure I was trying to work from, since there were duplicates in the original connections graph.

Better is to use a data structure like this:

connections = {1: [4, 5], 2: [5], 3: [4], 4: [1, 3, 5], 5: [1, 2, 4]} 

Then the following two algorithms can be used from https://www.python.org/doc/essays/graphs/

def find_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if not graph.has_key(start):
        return None
    for node in graph[start]:
        if node not in path:
            newpath = find_path(graph, node, end, path)
            if newpath: return newpath
    return None

and for the full paths

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    if not graph.has_key(start):
        return []
    paths = []
    for node in graph[start]:
        if node not in path:
            newpaths = find_all_paths(graph, node, end, path)
            for newpath in newpaths:
                paths.append(newpath)
    return paths

Post a Comment for "Build All Hamiltonian Paths From An Edge List"