コード例 #1
0
ファイル: MSTPrim.py プロジェクト: snowtheghost/Algorithms
def MSTPrim(graph: WeightedGraph, root: Any) -> WeightedGraph:
    """
    Prim's algorithm to creating an MST from a weighted graph - a greedy algorithm taking all accessible edges from
    the currently considered vertices into account
    :param graph: a weighted graph of which we extract an MST from
    :param root: the first node to consider
    :return: an MST of the graph
    """
    vertices = graph.adjacency_list.keys()
    mst = WeightedGraph()
    priority = {}
    parent = {}
    for vertex in vertices:
        priority[vertex] = max(graph.weights.values())  # Acts as infinity
        parent[vertex] = None
    priority[root] = 0

    q = MinPriorityQueue()
    for vertex in vertices:
        q.insert(vertex, priority[vertex])

    while not q.is_empty():
        node = q.extract_min()
        u = node.value
        u_weight = node.priority
        mst.add_vertex(u)
        if parent[u] is not None:
            mst.add_weighted_edge(u, parent[u], u_weight)

        for v in graph.adjacency_list[u]:
            if v in q and graph.weights[(u, v)] < priority[v]:
                priority[v] = graph.weights[(
                    u, v)]  # update to the correct weight
                q.update_priority(v,
                                  priority[v])  # update to the correct weight
                parent[v] = u
    return mst