Introduction
Prim's Algorithm is one of the most important algorithms used to find a Minimum Spanning Tree (MST).
You are given:
- A weighted undirected graph
- n vertices
- Weighted edges
Goal:
Connect all vertices with minimum total cost.
Example
Input
0 -- 1 (2)
| /
| /
2
|
3
Edges:
0-1 = 2
0-3 = 6
1-2 = 3
1-3 = 82-3 = 7
Output
MST Cost = 11 Key Observation
Instead of sorting all edges, Prim's grows the MST one node at a time by always choosing the minimum weight edge.
Algorithm
- Start from any node.
- Add all neighboring edges into a min heap.
- Pick minimum weight edge.
- If node is already visited, skip it.
- Otherwise include it in MST.
- Add its neighbors into heap.
- Continue until all nodes are visited.
Dry Run
Start From Node 0
Cost = 0
Visited = {0}
Visited = {0}
Pick Edge (0,1)
Cost = 2
Visited = {0,1}
Visited = {0,1}
Pick Edge (1,2)
Cost = 2
Visited = {0,1}
Visited = {0,1}
Pick Edge (0,3)
Cost = 11
Visited = {0,1,2,3}
Visited = {0,1,2,3}
Answer:
11 Approach : Greedy + Min Heap
Prim's Algorithm starts from one node and keeps expanding the tree using the smallest available edge.
A Priority Queue helps efficiently select the minimum weight edge.