Minimum Spanning Tree
-
Let be an undirected graph.
A spanning tree of is a graph containing the same vertices as , and edges (called ) of that form a tree. (There there is exactly one path between any two vertices of .)
If is not connected, it has no spanning tree, but we can instead compute a spanning forest, or collection of spanning trees, having one tree for each connected component of .
-
If is weighted, then a minimum spanning tree of is a spanning tree of whose total weight (summed over all edges of ) is minimal. In other words, no other spanning tree of has a smaller total weight.
Kruskal’s Algorithm
-
Kruskal’s algorithm computes the minimum spanning tree of as follows:
-
Create a new graph with the same vertices as , but no edges (yet).
-
Make a list of all the edges in .
-
Sort the edges by weight, from least to greatest.
-
Iterate through the edges in sorted order.
For each edge : if and are not connected by a path in T, add to .
-
-
Since Kruskal’s algorithm never adds if some other path already connects and , is guaranteed to be a tree (if is connected) or a forest (if is not).
-
Sorting the edges takes time. To determining whether two edges are already connected by a path, we can use disjoint sets, so that all the iterations of the look take less than time.
-
The running time of Kruskal’s algorithm is on adjacency lists and on adjacency matrix (it takes time to make a list of all the edges).
Since we use adjacency lists when , , so we can also say that the running time of Kruskal’s algorithm for adjacency lists is .
-
Visualization:
Prim’s Algorithm
-
Prim’s algorithm computes the minimum spanning tree of as follows:
-
For all in , set , .
-
Create a new graph with the same vertices as , but no edges (yet).
-
Choose a vertex from . Set .
-
Make a priority queue of all the vertices, with distance as the priority.
-
While is not empty:
-
-
Add the edge to .
-
For each vertex such that and :
if , set and .
-
-
-
We begin with a single root vertex , and add edges connecting new vertices until they are all connected. We’ll use a “distance” variable for each vertex to keep track of the shortest edge so far for joining that vertex to the result tree T. We’ll also track which edge that is.
-
The total time for
removeMin
operations will be in . The total time forupdatePriority
operations will be in . So the total running time is in , which is .
-
Visualization: