Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

Hamiltonian Paths in Python with Arbitrary Starting Positions

I'm currently working on a project in my spare time where I need to check for the existence of a Hamiltonian path within a graph, however, it doesn't matter where the path begins or ends, only that one exists within the graph.

I copied this code from another user on here:

def hamilton(graph, start_v):
  size = len(graph)
  to_visit = [None, start_v]
  path = []
  while(to_visit):
    v = to_visit.pop()
    if v : 
      path.append(v)
      if len(path) == size:
        break
      for x in set(graph[v])-set(path):
        to_visit.append(None)
        to_visit.append(x)
    else:
      path.pop()
  return path

There is obviously a parameter for the starting value. Now my first instinct would be to just iterate the function and run it for every starting vertex, but since I'm going to be running this on graphs with 100+ vertices it would take ages to run to completion. I don't really need to know what the path through all of the vertices is, I just need to know that one exists if that helps.

How would I adapt this to give an arbitrary starting location?

question from:https://stackoverflow.com/questions/65900922/hamiltonian-paths-in-python-with-arbitrary-starting-positions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could insert a new "start" vertex into the graph, with edges to every other vertex, then search for a Hamiltonian path starting at this "start" vertex. If a path is found, then one exists in the original graph simply by deleting the "start" vertex from the beginning of the path; conversely, if there is a Hamiltonian path in the original graph starting from any vertex, then there will be one in the new graph starting at the "start" vertex.

That said, this won't actually be more efficient than just calling the existing algorithm once for each starting vertex, because the algorithm you have works by brute force anyway.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...