Prim's Algorithm for Minimum Spanning Tree

🚀 Day 28/100 — Problem: Minimum Spanning Tree (Prim’s Algorithm) Find the minimum cost to connect all nodes in a graph Concept: Greedy + Priority Queue - Start from any node - Always pick the smallest edge - Expand the tree step by step import heapq def prim(n, graph): visited = set() min_heap = [(0, 0)] # (weight, node) total_cost = 0 while min_heap: weight, node = heapq.heappop(min_heap) if node in visited: continue visited.add(node) total_cost += weight for neighbor, w in graph[node]: if neighbor not in visited: heapq.heappush(min_heap, (w, neighbor)) return total_cost What I learned: Greedy works when choosing the best local option builds the global solution Priority queue helps efficiently select the next best edge Time Complexity: O(E log V) #100DaysOfCode #DSA #Graphs #PrimsAlgorithm #CodingInterview #ProblemSolving #PlacementPrep #LearnInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories