We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
defgetCost(g_nodes,g_from,g_to,g_weight):# Uses Prim's algorithm to find minimal spanning tree starting from node 1, stop as soon as goal is is put in the tree. At each step record the weight of the longest edge. This weight is necessarily in the path from 1 to goal in the MSP, and will be the answer. If when the tree is done and goal is still not reached, it means no path exists.fromheapqimportheappush,heappop# adjacency matrixadj=[[]for_inrange(g_nodes+1)]foriinrange(len(g_weight)):adj[g_from[i]].append((g_weight[i],g_to[i]))adj[g_to[i]].append((g_weight[i],g_from[i]))# record which node is visitedvisited=[False,True]+[False]*(g_nodes-1)# adjacent edges to the tree so far. Use heap to find the one with lowest weight.adj_edge=[]foredgeinadj[1]:heappush(adj_edge,edge)maximum=float('-inf')whileTrue:# pop the adjacent edge with lowest weightnew_weight,new_node=heappop(adj_edge)whilevisited[new_node]:iflen(adj_edge)==0:print('NOPATHEXISTS')returnnew_weight,new_node=heappop(adj_edge)visited[new_node]=Truemaximum=max(maximum,new_weight)# if the new node just added is the goal, then we're doneifnew_node==g_nodes:print(maximum)return#update adjacent edgesforedgeinadj[new_node]:heappush(adj_edge,edge)#use adjacency matrix and heap
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Jack goes to Rapture
You are viewing a single comment's thread. Return to all comments →
Prim's Algorithm and heap