0

I am trying to implement a recursive search for a Hamiltonian Path in a simple DAG. Here's my toy data and code:

DAG in edge-list format

4 5
1 2
3 1
3 2
4 3
4 2

DAG in dictionary format after converting

{1: [2], 3: [1, 2], 4: [3, 2]}

Code: G is the graph, size is the number of vertices in the graph, v is the current vertex, v_next is the neighbor vertex.

def hamilton(G, size, v, path=[]):
    if v not in set(path):  
        path.append(v)
        if len(path) == size:
            return path
        for v_next in G.get(v, []):
            cur_path = [i for i in path]
            result = hamilton(G, size, v_next, cur_path)
            if result is not None:  
                return result
    else:
        print('')

When I looped through the vertex (from 1 to 4) and run the function at each loop, the result is kind of weird.

for vertex in range(1, v+1):
    result = hamilton(graph, v, vertex)
    print(result)

None
None
None
[1, 2, 3, 4]

I expect the result would be [4, 3, 1, 2] when starting from 4. One post mentioned before this is because "mutable default arguments" problem. But I do not know how to solve in this case. Any hints?

nosense
  • 180
  • 1
  • 6
  • 16
  • Are you sure you posted the correct code? When I run your code the path is `[4, 3, 1, 2]`, just as expected. What exactly are you printing? Can you add the code that prints? – Daniel Junglas Dec 13 '19 at 10:37
  • Did you loop through all of the vertex? Or you just started at 4? I added the print code@DanielJunglas – nosense Dec 13 '19 at 15:33
  • I just ran `path = hamilton(G, 4, 4)` and that gave the expected results. – Daniel Junglas Dec 13 '19 at 17:20
  • That would work for simple graph. But for graph with dozens of vertices and hundreds of edges, it does not work. I have to loop through every vertices and then select the path. Weird things happened. Even for this simple graph, if you loop through all of the vertices, the result is different. – nosense Dec 13 '19 at 17:30

0 Answers0