The user wants a program that implements Prim's Minimum Spanning Tree (MST) algorithm.
-
Analyze the Request:
- Goal: Implement Prim's Algorithm.
- Input: A graph (usually represented as an adjacency matrix or adjacency list).
- Output: The MST edges and their total weight.
- Language: Not specified. Python is a good default for readability, but C++ or Java are common for algorithms. I'll provide a Python implementation because it's pseudocode-like and easy to understand, but I should probably mention the complexity. Actually, providing both a simple version and an optimized version (using a priority queue) is better for educational purposes.
-
Understand Prim's Algorithm:
- It's a greedy algorithm.
- Steps:
- Initialize a
key array with infinity (representing the minimum weight edge connecting a vertex to the current MST) and parent array as -1. key[0] = 0 (start at any node).
- Initialize an
mstSet (or visited set) to keep track of vertices included in the MST.
- Pick the vertex
u not in mstSet with the minimum key value.
- Add
u to mstSet.
- Update
key and parent values of all adjacent vertices v of u. If the weight of edge u-v is less than key[v], update key[v] and set parent[v] = u.
- Repeat until all vertices are in
mstSet.
-
Determine the Implementation Approach:
- Approach 1: Adjacency Matrix + Linear Search for min key. Time Complexity: O(V2). Good for dense graphs or simple demonstration.
- Approach 2: Adjacency List + Priority Queue (Min Heap). Time Complexity: O(ElogV) or O(E+VlogV). Better for sparse graphs and more standard in competitive programming/production.
I will write the O(ElogV) version using a priority queue (heapq in Python) because it's the more robust and generally "correct" way to implement it for graph problems, though the matrix version is easier to map directly to textbook pseudocode.
Wait, let's stick to the standard Python implementation that is readable.
Let's go with the Adjacency List + Priority Queue approach. It's efficient and Pythonic.
Data Structures:
- Graph: Dictionary or List of Lists where
graph[u] contains (weight, v).
- Visited: Set.
- Min-Heap: Stores
(weight, u, v). Initially [(0, start_node, None)].
-
Drafting the Code (Mental or Scratchpad):
import heapq
def prims_mst(graph, start_node):
mst = []
visited = set()
min_heap = [(0, start_node, None)] # (weight, current_node, parent_node)
total_weight = 0
while min_heap and len(visited) < len(graph):
weight, u, parent = heapq.heappop(min_heap)
if u in visited:
continue
visited.add(u)
if parent is not None:
mst.append((parent, u, weight))
total_weight += weight
for v, w in graph[u]: # graph[u] returns list of (neighbor, weight)
if v not in visited:
heapq.heappush(min_heap, (w, v, u))
return mst, total_weight
-
Refining the Code:
- The graph representation needs to be clear.
- Need a driver code block to test it.
- Comments are important.
Alternative Approach (Adjacency Matrix):
Some users specifically look for the logic min_key function found in textbooks (CLRS). However, the heap approach is more practical. I will provide the Heap approach as the primary solution, as it's standard.
Self-Correction during drafting: The heap might contain outdated entries for visited nodes. The check if u in visited: continue handles that cleanly.
-
Structuring the Output:
- Explanation: Briefly explain the logic (Greedy, Growing Tree).
- The Code: Python code using
heapq.
- Example Usage: Define a sample graph and print the result.
- Complexity Analysis: Mention Time Complexity (O(ElogV)).
-
Writing the Python Code:
- Define
prims_algorithm(vertices, edges) or prims_algorithm(graph). Let's stick to an adjacency list graph input for flexibility.
- Let's make the function self-contained.
Revised Code Plan:
- Import
heapq.
- Function
prim(n, graph) where n is number of nodes.
- Use adjacency list.
- Output: list of edges
(u, v, weight).
-
Final Polish:
- Ensure variable names are descriptive (
mst_edges, visited_nodes).
- Check edge cases: Disconnected graph? The loop
while min_heap will just finish early. I should probably check if len(visited) == n at the end to verify if a spanning tree exists.
Let's write the actual code response.
Code structure:
import heapq
def prim(n, graph):
# ...
Let's actually write the solution now.
Refining the graph input style:
Often these problems are given with nodes 0 to N-1.
Input:
adj = {0: [(1, 10), (2, 1)], ...}
This is easy to use.
Let's implement the standard version.
Step-by-step implementation plan:
- Initialization:
visited set, edges list for result, min_heap.
- Start: Push
(0, 0, -1) (cost, node, parent). Or handle the first node specially to avoid adding a dummy edge to the MST list. Let's use (0, start_node, None).
- Loop: While heap is not empty:
a. Pop min.
b. If visited, continue.
c. Mark visited.
d. Add edge to MST (if parent exists).
e. Iterate neighbors. If not visited, push to heap.
- Output: Print MST and Total Weight.
-
Final Code Check:
- Does it handle weights correctly? Yes.
- Does it handle node indexing (0-based vs 1-based)? Code is agnostic, but example should be clear.
- Is it Python 3? Yes.
I will also briefly mention the Adjacency Matrix approach (O(V2)) just in case they are a student looking for the exact textbook array-based implementation, but I'll implement the efficient one. Actually, sticking to one clear, efficient implementation is better. I will implement the Adjacency List with Priority Queue method.
Self-Correction: The prompt asks for "Prim's algorithm". It doesn't specify language. Python is the safest bet for readability. I will assume Python.
Let's double check the logic.
If graph is:
0 --(2)-- 1
| |
(1) (3)
| |
2 --(4)-- 3
Start 0.
Heap: [(0, 0, None)]
Pop (0, 0, None). Visited {0}.
Neighbors: 1 (w=2), 2 (w=1).
Heap: [(1, 2, 0), (2, 1, 0)].
Pop (1, 2, 0). Visited {0, 2}. MST Edge: 0-2 (1).
Neighbors of 2: 0 (skip, visited), 3 (w=4).
Heap: [(2, 1, 0), (4, 3, 2)].
Pop (2, 1, 0). Visited {0, 2, 1}. MST Edge: 0-1 (2).
Neighbors of 1: 0 (skip), 3 (w=3).
Heap: [(3, 3, 1), (4, 3, 2)].
Pop (3, 3, 1). Visited {0, 2, 1, 3}. MST Edge: 1-3 (3).
Done.
Total weight: 1 + 2 + 3 = 6. Correct.
One optimization note: In Python, checking if neighbor not in visited before pushing to heap reduces heap size, but checking inside the pop (lazy deletion) is also valid. Checking before push is slightly more efficient memory-wise.
This implementation uses an Adjacency List to represent the graph and a Min-Heap (Priority Queue) to efficiently select the next edge with the smallest weight. This approach has a time complexity of O(ElogV), where E is the number of edges and V is the number of vertices.
Python Implementation
import heapq
def prims_algorithm(graph, start_node):
"""
Implements Prim's algorithm to find the Minimum Spanning Tree (MST)
of a weighted undirected graph.
Args:
graph (dict): Adjacency list representation of the graph.
Format: {node: [(neighbor, weight), ...], ...}
start_node: The node to begin building the MST from.
Returns:
tuple: (total_weight, mst_edges)
total_weight (int/float): Sum of weights of the MST.
mst_edges (list): List of tuples (u, v, weight) representing edges in the MST.
"""
# Nodes visited so far
visited = set()
# Min-heap to store edges available for expansion.
# Format: (weight, current_node, parent_node)
min_heap = []
# List to store the edges of the MST
mst_edges = []
# Total weight of the MST
total_weight = 0
# Initialize heap with the start node (weight 0, no parent)
# We push (0, start_node, None)
heapq.heappush(min_heap, (0, start_node, None))
while min_heap:
# Get the edge with the smallest weight connecting the visited set
# to an unvisited node
weight, current_node, parent_node = heapq.heappop(min_heap)
# If the node has already been visited, skip it
if current_node in visited:
continue
# Mark the node as visited
visited.add(current_node)
# If it's not the start node, add the edge to our MST results
if parent_node is not None:
mst_edges.append((parent_node, current_node, weight))
total_weight += weight
# Iterate over neighbors of the current node
for neighbor, edge_weight in graph.get(current_node, []):
# If the neighbor hasn't been visited, add the edge to the heap
if neighbor not in visited:
heapq.heappush(min_heap, (edge_weight, neighbor, current_node))
return total_weight, mst_edges
# --- Example Usage ---
if __name__ == "__main__":
# Example Graph (Undirected)
# We must add edges in both directions (u->v and v->u)
example_graph = {
'A': [('B', 10), ('C', 1)],
'B': [('A', 10), ('C', 3), ('D', 2)],
'C': [('A', 1), ('B', 3), ('D', 8), ('E', 5)],
'D': [('B', 2), ('C', 8), ('E', 4)],
'E': [('C', 5), ('D', 4)]
}
print("Running Prim's Algorithm starting from node 'A'...")
weight, mst = prims_algorithm(example_graph, 'A')
print(f"\nTotal MST Weight: {weight}")
print("Edges in MST:")
for u, v, w in mst:
print(f"{u} -- {v} (Weight: {w})")
How it Works
-
Data Structures:
visited: A set to keep track of nodes already included in the MST.
min_heap: A priority queue that stores potential edges we can traverse, sorted by weight.
mst_edges: A list to store the final tree structure.
-
Initialization:
- We pick an arbitrary starting node (
start_node).
- We push a "dummy" edge into the heap with weight 0 to kickstart the process.
-
The Loop:
- We pop the edge with the lowest weight from the heap.
- If the node this edge connects to is already in
visited, we ignore it (this handles outdated entries in the heap).
- Otherwise, we add the node to
visited and record the edge connecting it to the tree.
- We then look at all neighbors of this new node. For any neighbor that isn't already visited, we push the connecting edge into the heap.
-
Complexity:
- Using a min-heap allows us to fetch the minimum weight edge in O(logV) time.
- Since we process every edge at most twice (once for each direction), the total time complexity is .