gpt4 book ai didi

python - 从边缘列表构建所有哈密顿路径

转载 作者:行者123 更新时间:2023-11-28 17:38:01 25 4
gpt4 key购买 nike

我无法从相关元组列表中找到构建树路径的方法?我只想要一个列表,其中包含每个节点被访问一次的每条路径,也就是哈密顿路径。

我一直在接近但错过了一些路径。

例如,假设我们有这个连接列表:

connections = [(1, 4), (1, 5), (2, 5), (3, 4), (4, 1), (4, 3), (4, 5), (5, 1), (5, 2), (5, 4)]

期望的输出:

[[1,4,3], [1,4,5,2], [1,5,2], [1,5,4,3], 
[2,5,1,4,3], [2,5,4,1], [2,5,4,3],
[3,4,1,5,2], [3,4,5,1], [3,4,5,2],
[4, 3], [4,1,5,2], [4,5,1], [4,5,2],
[5, 2], [5,1,4,3], [5,4,1], [5,4,3]
]

所以每条可能的路径都被存储并且每个节点只被访问一次:

这是我所拥有的,但缺少很多路径:

def find_paths(current_vertex):
if current_vertex not in current_path:
current_path.append(current_vertex)

possible_next_verticies = [v2 for v1,v2 in connections if v1 == current_vertex]

# if the current vertex is in the current_path
if current_vertex in current_path:
# if all the possible_next_vertices are in the current_path, return
adjacencies = [v for v in possible_next_verticies if v not in current_path]
if not adjacencies:
print "current_path: %s" % current_path
if current_path not in TESTED_PATHS:
TESTED_PATHS.append(current_path)
current_path.remove(current_vertex)
return

for next_vertice in possible_next_verticies:
if next_vertice not in current_path:
current_path.append(next_vertice)
find_paths(next_vertice)
continue
else:
continue

return current_path

最佳答案

好吧,由于我尝试使用的数据结构,我遇到了很多麻烦,因为原始连接图中存在重复项。

更好的方法是使用这样的数据结构:

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

那么从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

完整路径

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

关于python - 从边缘列表构建所有哈密顿路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28518369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com