To solve the problem of finding the Minimum Spanning Tree (MST) using Prim's Algorithm, we can follow these steps:
Prim's Algorithm Overview
Prim's algorithm builds the MST by starting from an arbitrary vertex and iteratively adding the edge with the smallest weight that connects a vertex in the MST to one outside it. This process continues until all vertices are included in the MST.
Approach
We use an adjacency list to represent the graph. The algorithm involves:
-
Initialization:
key[]: Stores the minimum weight edge connecting each vertex to the MST (initialized to infinity except the starting vertex, which is 0).parent[]: Tracks the parent of each vertex in the MST (to reconstruct the MST edges).mstSet[]: Marks vertices included in the MST (initialized toFalse).
-
Iterative Selection:
- For each vertex, select the vertex with the smallest key value not in the MST.
- Add this vertex to the MST.
- Update the key values of its adjacent vertices if a smaller weight edge exists.
-
Reconstruct MST:
- Use the
parent[]array to print the edges of the MST and calculate the total weight.
- Use the
Solution Code
This implementation uses a linear scan to find the minimum key vertex (suitable for small/dense graphs):
def prim_mst(adj, V):
# Initialize key, parent, and mstSet arrays
key = [float('inf')] * V
parent = [-1] * V
mstSet = [False] * V
# Starting vertex (0) has key 0
key[0] = 0
for _ in range(V):
# Find the vertex with the minimum key value not in MST
min_key = float('inf')
u = -1
for i in range(V):
if not mstSet[i] and key[i] < min_key:
min_key = key[i]
u = i
# Add the selected vertex to MST
mstSet[u] = True
# Update key values of adjacent vertices
for v, weight in adj[u]:
if not mstSet[v] and weight < key[v]:
key[v] = weight
parent[v] = u
# Print the MST edges and total weight
print("Edge \tWeight")
total_weight = 0
for v in range(1, V):
print(f"{parent[v]} - {v} \t {key[v]}")
total_weight += key[v]
print(f"Total Weight of MST: {total_weight}")
# Example usage
if __name__ == "__main__":
# Adjacency list representation of the graph
V = 5
adj = [
[(1, 2), (3, 6)], # Vertex 0
[(0, 2), (2, 3), (3, 8), (4,5)], # Vertex1
[(1,3), (4,7)], # Vertex2
[(0,6), (1,8), (4,9)], # Vertex3
[(1,5), (2,7), (3,9)] # Vertex4
]
prim_mst(adj, V)
Explanation
- Initialization: The starting vertex (0) has a key value of 0, others are infinity.
- Vertex Selection: For each iteration, we pick the vertex with the smallest key not in the MST (e.g., 0 →1 →2 →4 →3).
- Key Update: For each adjacent vertex of the selected vertex, we update its key if the edge weight is smaller than the current key.
- Output: The MST edges are printed using the parent array, and the total weight is calculated.
This approach has a time complexity of O(V²) (linear scan for min key) which is efficient for dense graphs. For sparse graphs, a heap-based approach (O(E log V)) is better, but the linear scan is simpler for beginners.
Output:
The code will print the MST edges and their weights, along with the total weight of the MST. For the example, the output is:
Edge Weight
0 -1 2
1 -2 3
0 -3 6
1 -4 5
Total Weight of MST:16
This is the correct MST for the given graph.
Answer: The implementation of Prim's Algorithm as shown above.

作者声明:本文包含人工智能生成内容。