Prim's algo
Sat Sep 30 2023 05:50:38 GMT+0000 (Coordinated Universal Time)
Saved by
@utp
#User function Template for python3
import heapq
class Solution:
#Function to find sum of weights of edges of the Minimum Spanning Tree.
def spanningTree(self, V, adj):
#code here
#MST
sum_=0
adjl = adj
vis = [0]*V
pq = [] #wt,node #store parent as well when the mst is asked as well
heapq.heappush(pq,[0,0])
while pq:
cost,node = heapq.heappop(pq)
if vis[node]==1:continue
sum_+=cost
vis[node] = 1
for ch,wt in adjl[node]:
if vis[ch]==0:heapq.heappush(pq,[wt,ch])
return sum_
content_copyCOPY
Comments