Prim's (MST) : Special Subtree

  • + 1 comment

    python3

    def prims(n, edges, start):
        
        mst = {start}
        total = 0
        edges.sort(key=lambda x: x[2])
    
        # Prim: Add lowest weight edge that starts anywhere in the mst and ends on any of the remaining vertices (guarantees no cycles), until no vertices remain.
        while len(mst) < n:
            for u, v, w in edges:
                if (u in mst) ^ (v in mst):
                    mst = mst.union({u, v})
                    total += w
                    break
        return total