def dijkstra(graph, root):
    vertices = graph.keys()
    n = len(vertices)

    # Initialize the priority queue
    inf = float("inf")
    pq = MinHeap([(v, inf) for v in graph.keys()])
    pq.change_priority(root, 0)
    # Other initializations
    parent = collections.defaultdict(lambda: None)
    selected = set()
    cost = collections.defaultdict(lambda: inf)
    cost[root] = 0

    while len(selected) < n:
        u = pq.min()
        du = cost[u] = pq.get_priority(u)
        selected.add(u)
        pq.take_min()
        for (v, w) in graph[u].items():
            if v not in selected and pq.get_priority(v) > du + w:
                pq.change_priority(v, du + w)
                parent[v] = u

    return cost, parent
def dijkstra(graph, root):
    vertices = graph.keys()
    n = len(vertices)

    # Initialize the priority queue
    inf = float("inf")
    pq = MinHeap([(v, inf) for v in graph.keys()]) 
    pq.change_priority(root, 0)
    # Other initializations
    parent = collections.defaultdict(lambda: None)
    selected = set()
    cost = collections.defaultdict(lambda: inf)
    cost[root] = 0

    while len(selected) < n:
        u = pq.min()
        du = cost[u] = pq.get_priority(u)
        selected.add(u)
        pq.take_min()
        for (v, w) in graph[u].items():
            if v not in selected and pq.get_priority(v) > du + w:
                pq.change_priority(v, du + w)
                parent[v] = u
    
    return cost, parent
def prim(graph, root):
    vertices = graph.keys()
    n = len(vertices)

    # Initialize the priority queue
    inf = float("inf")
    pq = MinHeap([(v, inf) for v in graph.keys()]) 
    pq.change_priority(root, 0)
    # Other initializations
    parent = collections.defaultdict(lambda: None)
    selected = set()
    cost = 0
    mst = []

    while len(selected) < n:
        u = pq.take_min()
        selected.add(u)
        for (v, w) in graph[u].items():
            if not v in selected and w < pq.get_priority(v):
                pq.change_priority(v, w)
                parent[v] = u
        pu = parent[u]
        if pu != None:
            mst.append( (min(u,pu), max(u,pu)) )
            cost += graph[u][pu]
    
    return cost, mst
Exemple #4
0
def prim(graph, root):
    vertices = graph.keys()
    n = len(vertices)

    # Initialize the priority queue
    inf = float("inf")
    pq = MinHeap([(v, inf) for v in graph.keys()])
    pq.change_priority(root, 0)
    # Other initializations
    parent = collections.defaultdict(lambda: None)
    selected = set()
    cost = 0
    mst = []

    while len(selected) < n:
        u = pq.take_min()
        selected.add(u)
        for (v, w) in graph[u].items():
            if not v in selected and w < pq.get_priority(v):
                pq.change_priority(v, w)
                parent[v] = u
        pu = parent[u]
        if pu != None:
            mst.append((min(u, pu), max(u, pu)))
            cost += graph[u][pu]

    return cost, mst