imashutosh51

Minimum Spanning Trees(Prims Algorithm)

Mar 23rd, 2026 (edited)
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.26 KB | None | 0 0
  1. #spanning Tree: For N nodes there should be N-1 edges and all the nodes must reach to each other.There can be multiple spanning tree for the same graph.
  2. #Minimum spanning Tree: out of all the spanning tree, MST is the one which has the minimum sum of the weights of the edges.
  3. """
  4. Intuition for Prim's Algorithm (Minimum Spanning Tree)
  5.  
  6. Step 1: Identify the Problem Type
  7. ---------------------------------
  8. A Minimum Spanning Tree (MST) is a subset of edges that connects all
  9. vertices in a graph without cycles and with the minimum total weight.
  10. Since we want to build this tree 'greedily' by always picking the
  11. next cheapest available edge that connects a new node, we use
  12. Prim's Algorithm.
  13.  
  14. Step 2: Key Data Structures
  15. ---------------------------
  16. 1. Priority Queue (Min-Heap): Stores (weight, node, parent). It helps
  17.   us always pick the edge with the smallest weight available.
  18. 2. Visited Array: Keeps track of nodes already included in the MST
  19.   to prevent cycles.
  20. 3. Sum: To store the total weight of the MST.
  21. 4. MST List: (Optional) To store the actual edges (u, v) that form the tree.
  22.  
  23. Step 3: Initial Configuration
  24. -----------------------------
  25. - Start with any node (usually node 0).
  26. - Push (0, 0, -1) into the Priority Queue: (weight=0, node=0, parent=-1).
  27. - Visited array is initially all 0s.
  28.  
  29. Step 4: The Greedy BFS-like Loop
  30. --------------------------------
  31. While the Priority Queue is not empty:
  32. 1. Extract the element with the minimum weight from the Min-Heap.
  33. 2. Check if the node is already visited:
  34.   - If YES: Ignore it (it's already part of the MST via a cheaper edge).
  35.   - If NO: Mark it as VISITED. This node is now officially in our MST.
  36.  
  37. Step 5: Adding to Results
  38. -------------------------
  39. - Add the edge weight to our running 'Sum'.
  40. - If parent != -1, add the edge (parent, node) to our MST List.
  41.  
  42. Step 6: Exploring Neighbors
  43. ---------------------------
  44. For the current node, look at all its adjacent neighbors:
  45. - If a neighbor is NOT visited:
  46.  - Push (edge_weight, neighbor_node, current_node) into the Priority Queue.
  47. - Note: We don't mark neighbors as visited here! We only mark them
  48.  visited when they are 'popped' from the Priority Queue. This
  49.  allows a later, cheaper edge to potentially 'overtake' a more
  50.  expensive one.
  51.  
  52. Step 7: Complexity
  53. ------------------
  54. - Time: O(E * log E) or O(E * log V) - Each edge is pushed/popped
  55.  from the Priority Queue.
  56. - Space: O(V + E) - For the adjacency list, visited array, and
  57.  Priority Queue.
  58. """
  59.  
  60. from heapq import heappush, heappop
  61. from collections import defaultdict
  62. class Solution:
  63.     def spanningTree(self, v, edges):
  64.         adj=defaultdict(list)
  65.         for a,b,c in edges:
  66.             adj[a].append((b,c))
  67.             adj[b].append((a,c))
  68.         need=v #because starting node also got included with 0 weight so v
  69.         mst=0
  70.         heap=[]
  71.         heappush(heap,(0,0)) #(cost,node)
  72.         visited=[False]*v
  73.         while heap and need>0:
  74.             cost,node=heappop(heap)
  75.             if visited[node]==True:
  76.                 continue
  77.             mst+=cost
  78.             visited[node]=True
  79.             need-=1
  80.             for neigh,w in adj[node]:
  81.                 if visited[neigh]==False:
  82.                     heappush(heap,(w,neigh))
  83.         return mst  
Advertisement
Add Comment
Please, Sign In to add comment