10. Minimum Cost Spanning Tree (MST)
Definition:
A Minimum Spanning Tree of a connected, weighted, undirected graph is a subset of edges that connects all vertices with the minimum total edge weight, without any cycles. It has exactly V-1 edges.
10a. Prim's Algorithm
Strategy: Start from any vertex, greedily add the cheapest edge that connects a visited vertex to an unvisited vertex.
Steps:
1. Start with any vertex (mark it visited)
2. From all edges connecting visited to unvisited vertices, pick the minimum weight edge
3. Add that edge to MST, mark the new vertex as visited
4. Repeat until all vertices are visited
Q: Find MST using Prim's for graph with edges:
(A-B,4), (A-C,3), (B-C,1), (B-D,2), (C-D,4), (D-E,2), (C-E,6)
Solution (Starting from vertex A):
Step 1: Start at A. Visited = {A}
Edges from A: A-B(4), A-C(3) β Pick A-C(3)
MST edges: {A-C(3)}, Visited = {A, C}
Step 2: Edges from {A,C}: A-B(4), B-C(1), C-D(4), C-E(6) β Pick B-C(1)
MST edges: {A-C(3), B-C(1)}, Visited = {A, C, B}
Step 3: Edges from {A,C,B}: B-D(2), C-D(4), C-E(6) β Pick B-D(2)
MST edges: {A-C(3), B-C(1), B-D(2)}, Visited = {A, C, B, D}
Step 4: Edges from {A,C,B,D}: C-E(6), D-E(2) β Pick D-E(2)
MST edges: {A-C(3), B-C(1), B-D(2), D-E(2)}, Visited = {A, C, B, D, E}
MST Total Cost = 3 + 1 + 2 + 2 = 8
MST Edges: A-C, B-C, B-D, D-E
Prim's Time Complexity:
Adjacency Matrix: O(VΒ²)
Min-Heap + Adj List: O(E log V)
Fibonacci Heap: O(E + V log V)
10b. Kruskal's Algorithm
Strategy: Sort ALL edges by weight, then greedily pick smallest edge that doesn't form a cycle (using Union-Find/Disjoint Set).
Steps:
1. Sort all edges in ascending order of weight
2. Pick the smallest edge. If it doesn't form a cycle, add to MST
3. Repeat until MST has V-1 edges
Q: Find MST using Kruskal's for the same graph:
(A-B,4), (A-C,3), (B-C,1), (B-D,2), (C-D,4), (D-E,2), (C-E,6)
Solution:
Step 1: Sort edges by weight:
B-C(1), B-D(2), D-E(2), A-C(3), A-B(4), C-D(4), C-E(6)
Step 2: Pick edges greedily:
Edge B-C(1) β No cycle β Add β MST = {B-C}
Edge B-D(2) β No cycle β Add β MST = {B-C, B-D}
Edge D-E(2) β No cycle β Add β MST = {B-C, B-D, D-E}
Edge A-C(3) β No cycle β Add β MST = {B-C, B-D, D-E, A-C}
(V-1 = 4 edges selected β STOP)
MST Total Cost = 1 + 2 + 2 + 3 = 8 β (Same as Prim's!)
Kruskal's Time Complexity:
O(E log E) or O(E log V) β dominated by sorting edges
| Property | Prim's | Kruskal's |
| Approach | Vertex-based (grows MST) | Edge-based (picks edges) |
| Data Structure | Priority Queue / Min-Heap | Union-Find (Disjoint Sets) |
| Better for | Dense graphs | Sparse graphs |
| Time (Adj Matrix) | O(VΒ²) | O(E log E) |
| Starts from | Any single vertex | Sorted edge list |