Prim's (MST) : Special Subtree

  • + 0 comments
    import os
    def mim(key, mst):
        mini = float('+inf')
        index = 0
        for i in range(1, len(key)):
            # print("I",key[i])
            if not mst[i] and key[i] < mini:
                mini = key[i]
                index = i
        # print("ndggkndg",index,mini)
        return index
    
    def prims(n, edges, s):
        adjList = {v: [] for v in range(1, n+1)}
        
        for u, v, w in edges:
            adjList[u].append((v, w))
            adjList[v].append((u, w))
        parent =[0]*(n+1)
        key = [float('+inf')]*(n+1)
        mst = [False]*(n+1)
        key[s]=0
        parent[s]=-1
        mst[0]= True
        
        while not all(mst):
            node = mim(key, mst)
            # print("node",node)
            mst[node] = True
            for x, z in adjList[node]:
                # print(node,x,key[x])
                if mst[x]==False and key[x] >z:
                    # print(node, x,key[x])
                    key[x]=z
                    parent[x] = node
        # print(key)
        # print(parent)
        return sum(key[1:])