Prim的算法无法生成适当的生成树

时间:2019-08-12 14:43:47

标签: python

def prim(graph):
    que = queue.PriorityQueue()
    mst = []
    visited = set()

    # Generate edge information with tuple and push it to Priority Queue
    for outer_key in graph.keys():
        for inner_key, inner_cost in graph[outer_key].items():
            que.put((inner_cost, outer_key, inner_key))

    while que.empty() is False:
        edge = que.get()
        cost, frm, to = edge

        if to in visited:
            continue

        visited.add(frm)
        visited.add(to)
        mst.append(edge)

        for next_to, cost in graph[to].items():
            if next_to not in visited:
                que.put((cost, to, next_to))

    return mst

Full source code

我正在使用Python创建非常简单的Prim算法。在此代码中,图是使用嵌套字典制作的。我将所有边(元组)推入优先级队列,从中逐一获取它们,检查它是否是一个访问过的顶点,然后将相邻的顶点推入优先级队列。

但是,最终生成树的形状如下:

                   2
  [A]        [B]-------[C]
   |
 5 |
   |
  [D]--------[E]       [F]
         6              |
                    +---+
                    | 3
             [G]----+ 

我想知道问题出在哪里以及如何解决。谢谢。

1 个答案:

答案 0 :(得分:1)

Prim的算法从任意顶点开始。然后将其所有边缘添加到优先级队列中,并开始循环。

您将所有的边缘添加到了队列中(也许您与Kruskal混淆了,后者做了其他事情)。

因此,有效的代码是:

def prim(graph):
    que = queue.PriorityQueue()
    mst = []
    visited = set()

    # Generate edge information with tuple and push it to Priority Queue
    #for outer_key in graph.keys():
    #    for inner_key, inner_cost in graph[outer_key].items():
    #        que.put((inner_cost, outer_key, inner_key))

    starting_vertex = list(graph.keys())[0]

    for next_to, cost in graph[starting_vertex].items():
        if next_to not in visited:
            que.put((cost, starting_vertex, next_to))

    while que.empty() is False:
        edge = que.get()
        cost, frm, to = edge

        if to in visited:
            continue

        visited.add(frm)
        visited.add(to)
        mst.append(edge)

        for next_to, cost in graph[to].items():
            if next_to not in visited:
                que.put((cost, to, next_to))

    return mst