Prim’s Algorithm is a greedy algorithm used to fin...
Prim’s Algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of a weighted, connected, and undirected graph. A Minimum Spanning Tree is a subset of the edges that connects all the vertices together with the minimum possible total edge weight, without forming any cycles. How Prim’s Algorithm Works Start with any arbitrary vertex (usually node 0 or 1). Select the smallest edge connecting the selected vertex to an unselected vertex. Add the selected edge to the MST and mark the new vertex as visited. Repeat the process until all vertices are included in the MST. Algorithm Steps Choose any starting vertex. Initialize a min heap (priority queue) to store edges. Use a visited array to keep track of included vertices. Keep adding the smallest edge connecting a visited and unvisited vertex. Repeat until all vertices are included. Time Complexity O(E log V) using a priority queue (Binary Heap). O(V²) using an adjacency matrix (for dense graphs). Example Consider this weighted graph: 2 A----B | | 4 | | 3 | | C----D 5 Step-by-step Execution Start at A, pick A–B (2). Pick the next smallest edge B–D (3). Pick D–C (5). Pick A–C (4). MST completed. Final MST Edges: (A-B) = 2 (B-D) = 3 (A-C) = 4 Total Weight = 2 + 3 + 4 = 9
Keywords
Subscribe for latest offers & updates
We hate spam too.