Overview
Prim’s algorithm finds a minimum spanning tree (MST) for a weighted undirected graph. An MST is a subset of edges that connects all vertices with the minimum total edge weight, without forming any cycles.This implementation works with both
AdjacencyListWeightedGraph and AdjacencyMatrixWeightedGraph from the DSA package.Functions
prims_mst
Computes the minimum spanning tree of a graph.prim.py:5
graph: The weighted graph to find an MST from (supports both adjacency list and matrix representations)start(str): The starting vertex labelmst_graph(optional): An empty graph object to populate with the MST. If not provided, a newAdjacencyListWeightedGraphis created
AdjacencyListWeightedGraph: The minimum spanning tree of the input graph
mst_weight
Calculates the total weight of a graph (typically an MST).prim.py:46
graph: The graph to calculate the total weight for
int: The sum of all edge weights in the graph
Usage Examples
Algorithm Details
The implementation uses:- Priority Queue: Efficiently selects the minimum weight edge (prim.py:30)
- Visited Set: Tracks which vertices have been added to the MST (prim.py:29)
- Edge Selection: Only adds edges that connect to unvisited vertices (prim.py:40)
- Helper Function:
add_adjacent()adds all edges from a vertex to the priority queue (prim.py:18-23)
Time Complexity
- Time Complexity: O((V + E) log V) where V is the number of vertices and E is the number of edges
- Space Complexity: O(V + E) for storing the MST and priority queue
The algorithm continues until all vertices are visited or the priority queue is empty (prim.py:36), ensuring that all reachable vertices are included in the MST.
Key Properties
- The resulting MST is always a tree (connected and acyclic)
- For a connected graph with V vertices, the MST contains exactly V-1 edges
- The total weight of the MST is minimal among all possible spanning trees
- The choice of starting vertex does not affect the total weight of the MST
Related
- Dijkstra’s Algorithm - Similar approach for finding shortest paths
- Graph Data Structure - Learn about graph representations
- Graph Visualization - Visualize MSTs