UNB/ CS/ David Bremner/ teaching/ cs3383/ lectures/ 21.0-demos/ prim.py
#!/usr/bin/env python3
from pqdict import pqdict
from math import inf

def prim(G,root):
    pq = pqdict(); prev = {}
    for v in G.keys():
        pq.additem(v,inf)
    pq.updateitem(root,0)
    while len(pq)>0:
        v = pq.pop()
        for (z,weight) in G[v]:
            if z in pq and weight < pq[z]:
                prev[z]=v
                pq.updateitem(z,weight)
    return prev

def as_dot(T):
    print("digraph G {")
    for v in T.keys():
        print ("\t{:s} -> {:s}".format(v,T[v]))
    print("}")

if __name__ == "__main__":    
    Graph = { 'A' : [('B',4),('C',1),('D',3)],
              'B' : [('A',4),('C',4),('D',4)],
              'C' : [('A',1),('B',4),('D',2),('F',4)],
              'D' : [('B',4),('C',2),('F',6)],
              'E' : [('F',5)],
              'F' : [('C',4),('D',6),('E',5)] }

    as_dot (prim(Graph,'A'))