Prim's (MST) : Special Subtree

  • + 0 comments

    Python

    def prims(n, edges, start):  
        connected = set([start])
        totalprice = 0
        while len(connected) < n:
            minprice = 10**6
            for e in edges:
                if (e[0] in connected and e[1] not in connected) or \
                   (e[1] in connected and e[0] not in connected):
                   if e[2] < minprice:
                       minprice = e[2]
                       edgeconnect = e
            connected.add(edgeconnect[0])
            connected.add(edgeconnect[1])
            totalprice += minprice            
        return totalprice