๐ณ Minimum Spanning Tree (MST)
You need to connect all cities with cable networks. Some connections are expensive, others cheap. What's the minimum cost to connect all cities? Minimum Spanning Tree finds the optimal network design!
The Connectivity Problem
Given a weighted graph, find a tree that connects all vertices with minimum total edge weight:
Real-World Applications
- Network Design: Connect all nodes with minimum cable cost
- Cluster Analysis: Group similar data points
- Approximation Algorithms: TSP approximation
- Image Segmentation: Connect similar pixels
- Circuit Design: Minimize wire connections
Two Algorithms for MST
1. Kruskal's Algorithm
Edge-Based Greedy
- Sort all edges by weight
- Add smallest edge that doesn't create cycle
- Use Union-Find to detect cycles
- Repeat until V-1 edges added
Time: O(E log E) - Best for sparse graphs
2. Prim's Algorithm
Vertex-Based Greedy
- Start from any vertex
- Add minimum edge from MST to non-MST vertex
- Use priority queue to find minimum edge
- Repeat until all vertices in MST
Time: O(E log V) - Best for dense graphs
See MST Algorithms in Action
Union-Find Data Structure
Used in Kruskal's
- Find(x): Find root with path compression
- Union(x, y): Merge sets using union by rank
- Cycle Detection: If Find(u) == Find(v), edge creates cycle!
- Time: O(ฮฑ(V)) amortized - Nearly constant!
The Complete Code
Output
Click Run to execute your code
Kruskal vs Prim
When to Use Each
| Aspect | Kruskal | Prim |
|---|---|---|
| Approach | Edge-based | Vertex-based |
| Time (Sparse) | O(E log E) | O(E log V) |
| Time (Dense) | O(E log E) | O(Vยฒ) |
| Best For | Sparse graphs | Dense graphs |
Summary
What You've Learned
MST connects all vertices with minimum total weight:
- Kruskal: Sort edges, add smallest (no cycle) - O(E log E)
- Prim: Start from vertex, add minimum edge - O(E log V)
- Union-Find: Efficient cycle detection in Kruskal's
- Both are greedy: Optimal solution guaranteed
- Applications: Network design, cluster analysis
- Key insight: Greedy choice (minimum edge) is always in MST
What's Next?
You've mastered MST! Next, we'll explore Advanced Graph Algorithms - Floyd-Warshall for all-pairs shortest path, strongly connected components, and finding critical network infrastructure!
Enjoying these tutorials?