从边缘列表构建所有汉密尔顿路径

从边缘列表构建所有汉密尔顿路径,第1张

从边缘列表构建所有汉密尔顿路径

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

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

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5648873.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存