Home
DSA Visualizer
Data Structures
Minimum Spanning Tree (MST)
Minimum Spanning Tree (MST)
A minimum spanning tree (MST) connects all vertices of a graph with the minimum total edge weight; Prim's and Kruskal's algorithms find it.
INIT
Tree so far — weight 0
No edge taken yet
Cheapest link into the tree
Every node starts unreachable except A, whose cost to join is 0.
Next
Start the tree at A.
Algorithm
Intuition
Prim's Algorithm: Imagine a mold spreading from a single point. It keeps adding the nearest node to the growing blob until everything is covered.
Kruskal's Algorithm: Imagine building bridges. You always build the cheapest bridge available anywhere on the map, unless it connects two islands that are already connected (which would be redundant).
Concept
A Spanning Tree is a subgraph that connects all vertices without any cycles. A Minimum Spanning Tree (MST) is the spanning tree with the lowest total edge weight.
- Prim's (Node-based): Grows a single tree from a starting node. Best for dense graphs.
- Kruskal's (Edge-based): Adds edges from lightest to heaviest, merging disjoint sets. Best for sparse graphs.
How it Works
- Start with an arbitrary node.
- Add all connected edges to a Priority Queue.
- Pick the smallest edge connecting a visited node to an unvisited one.
- Add the new node to the MST set.
- Repeat until all nodes are visited.
- Sort all edges by weight (ascending).
- Iterate through sorted edges.
- For each edge (u, v), check if u and v are already connected (using Union-Find).
- If not connected, add edge to MST and union the sets.
- If connected, skip to avoid cycles.
Step-by-Step Breakdown
Watch the visualization:
- Green edge: Part of the tree built so far.
- Blue edge: Currently being considered.
- Red edge (Kruskal's): Rejected because it would form a cycle.
- Green node: Already connected by the tree.
- Blue nodes (Prim's): Solid blue is the node the step works from and pale blue is the neighbour whose cheapest link is being checked; the number above a node is that cheapest link.
When to Use
Applications:
- Network design (telecom cables, water pipes, road networks).
- Clustering algorithms in Machine Learning.
- Approximation algorithms for NP-hard problems (like TSP).
When NOT to Use
- Shortest Paths: MST minimizes total weight, not the path distance between two specific nodes (use Dijkstra).
- Directed Graphs: Standard Prim's/Kruskal's apply to undirected graphs. For directed MST, use the Chu-Liu/Edmonds algorithm.
How to Identify
"Connect all points with minimum cost", "Design a network with least cable".
Applying for software engineering roles? Free, no sign-up:
