【问题标题】:Bug in Minimum Spanning Tree using Prim's algorithm使用 Prim 算法的最小生成树中的错误
【发布时间】:2020-04-17 05:32:36
【问题描述】:

我正在尝试实现 Prim 的算法,但每次运行时输出都会发生变化

{'A': {'C'}, 'B': {'A'}, 'F': {'G'}, 'E': {'B'}, 'D': {'E'}, 'C': {'F'}}

应该是什么时候

{'D': {'E'}, 'E': {'B'}, 'B': {'A'}, 'A': {'C'}, 'C': {'F'}, 'F': {'G'}}

不确定这里到底发生了什么,我尝试调试无济于事。有谁知道我是否遗漏了一些明显的东西?

from collections import defaultdict
import heapq


def create_spanning_tree(graph, starting_vertex):
    mst = defaultdict(set)
    visited = set([starting_vertex])
    edges = [
        (cost, starting_vertex, to)
        for to, cost in graph[starting_vertex].items()
    ]
    heapq.heapify(edges)
    while edges:
        cost, frm, to = heapq.heappop(edges)
        if to not in visited:
            visited.add(to)
            mst[frm].add(to)
            for to_next, cost in graph[to].items():
                if to_next not in visited:
                    heapq.heappush(edges, (cost, to, to_next))
    return mst

example_graph = {
    'A': {'B': 2, 'C': 3},
    'B': {'A': 2, 'C': 12, 'D': 10, 'E': 4},
    'C': {'A': 3, 'B': 12, 'F': 5},
    'D': {'B': 10, 'E': 7},
    'E': {'B': 4, 'D': 7, 'F': 16},
    'F': {'C': 5, 'E': 16, 'G': 9},
    'G': {'F': 9},
}
print(dict(create_spanning_tree(example_graph, 'D')))

【问题讨论】:

    标签: python python-3.x minimum-spanning-tree


    【解决方案1】:

    仔细观察两个输出,

    {'A': {'C'}, 'B': {'A'}, 'F': {'G'}, 'E': {'B'}, 'D': {'E'}, 'C': {'F'}}{'D': {'E'}, 'E': {'B'}, 'B': {'A'}, 'A': {'C'}, 'C': {'F'}, 'F': {'G'}} 是一样的。

    因为它是字典,所以(键,值)对很重要,这在答案中是相同的,而不是它们出现的顺序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多