在Petersen子图中找到一条哈密顿路径

2024-04-26 01:37:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始使用idejupyter&python3.6,有一个问题出现了。 我必须画出IDE,彼得森子图中的哈密顿路径,但我不知道怎么做。在

我展示了上述图表的信息:

你知道你该怎么评论吗?在

非常感谢。在


Tags: httpsorg路径信息wiki图表评论wikipedia
1条回答
网友
1楼 · 发布于 2024-04-26 01:37:45

要计算Petersen图中的哈密顿图,我们可以使用this answer中的解

petersen = {1: [2,5,6], 2: [3,1,7], 3: [4,2,8], 4: [5,3,9], 5: [1,4,10],
        6: [1,8,9], 7:[2,9,10], 8: [3,10,6], 9: [4,6,7], 10: [5,7,8]}

Petersen graph

我忘了彼得森图是否与它们的顶点置换同构,所以我假设它们不是。因此,我们将添加两个连接到原始图的每个顶点的新顶点,而不是搜索构成路径末端的成对顶点。因此,如果原图中存在一条哈密顿路径,那么它将存在于这个扩展图中,只要去掉两个额外的顶点(-1)和(-2)。在

^{pr2}$

现在我们可以应用帖子中的算法:

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    if not start in graph:
        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
for path in find_all_paths(petersen, -1, -2):
if len(path) == len(petersen):
    print(path[1:-1])
[1, 2, 3, 4, 5, 10, 7, 9, 6, 8]
[1, 2, 3, 4, 5, 10, 8, 6, 9, 7]
[1, 2, 3, 8, 6, 9, 4, 5, 10, 7]
[1, 2, 3, 8, 6, 9, 7, 10, 5, 4]
[1, 2, 7, 9, 6, 8, 3, 4, 5, 10]
[1, 2, 7, 9, 6, 8, 10, 5, 4, 3]
            ...

由于该算法返回给定顶点之间所有路径的列表,我们将仅将其过滤为哈密顿路径,并切断多余的顶点。在

当然,这可能更有效,但我将优化留给您或其他人。在我看来,对于像彼得森这样的小图形来说,它运行得很快。在

绘图

我们随机选择一条路径并将其存储在ham_path变量中。

import random
ham_paths = [path[1:-1] for path in find_all_paths(petersen, -1, -2) 
         if len(path) == len(petersen)]
ham_path = random.choice(ham_paths)

然后我们将使用networkx包来绘制图形和选择的路径。在

import networkx
g = networkx.Graph()
for k, vs in petersen.items():
    for v in vs:
        if v in [-1, -2] or k in [-1, -2]:
            continue
        if abs(ham_path.index(k) - ham_path.index(v)) == 1:
            g.add_edge(k,v, color='red', width=1.5)
        else:
            g.add_edge(k,v, color='black', width=0.5)

我们创建一个networkx图,哈密顿路径中的每条边都将被涂成红色和粗体。另一方面,每一个边缘都会变薄变黑。我们也不希望在我们的绘图中额外的顶点。在

pos = networkx.circular_layout(g)
edges = g.edges()
colors = [g[u][v]['color'] for u,v in edges]
widths = [g[u][v]['width'] for u,v in edges]
networkx.draw(g, pos, edges=edges, edge_color=colors, width=widths)

Hamiltonian path

相关问题 更多 >