Advertisement
Guest User

Prim's Algorithm for Minimum Spanning Tree

a guest
Nov 29th, 2015
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. # Prims algorithm
  2.  
  3.  
  4. from collections import defaultdict
  5. from heapq import *
  6.  
  7.  
  8. def prim( nodes, edges ):
  9. conn = defaultdict( list )
  10. for n1,n2,c in edges:
  11. conn[ n1 ].append( (c, n1, n2) )
  12. conn[ n2 ].append( (c, n2, n1) )
  13.  
  14.  
  15. mst = []
  16. used = set( nodes[ 0 ] )
  17. usable_edges = conn[ nodes[0] ][:]
  18. heapify( usable_edges )
  19.  
  20.  
  21. while usable_edges:
  22. cost, n1, n2 = heappop( usable_edges )
  23. if n2 not in used:
  24. used.add( n2 )
  25. mst.append( ( n1, n2, cost ) )
  26.  
  27.  
  28. for e in conn[ n2 ]:
  29. if e[ 2 ] not in used:
  30. heappush( usable_edges, e )
  31. return mst
  32.  
  33.  
  34. #test
  35. nodes = list("ABCDEFG")
  36. edges = [ ("A", "B", 7), ("A", "D", 5),
  37. ("B", "C", 8), ("B", "D", 9),
  38. ("B", "E", 7), ("C", "E", 5),
  39. ("D", "E", 15), ("D", "F", 6),
  40. ("E", "F", 8), ("E", "G", 9),
  41. ("F", "G", 11)]
  42.  
  43.  
  44. print "prim:", prim( nodes, edges )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement