The user wants a program implementing Prim's algorithm for finding a Minimum Spanning Tree (MST).
Understand the Goal: The objective is to take a graph (weighted, undirected) as input and output the set of edges that form the MST and the total weight of that tree.
Choose a Programming Language: Python is generally the most accessible and readable language for algorithmic demonstrations, but C++ or Java are also common. I will stick with Python for clarity, but maybe provide a C++ version if requested (no, just stick to Python for the primary answer, it's usually what people want for logic demonstration).
Algorithm Logic (Prim's):
Start with an arbitrary node (say node 0).
Maintain a set (or boolean array) of visited nodes.
Use a priority queue (min-heap) to store edges connected to the visited set, ordered by weight.
While the priority queue is not empty and the MST is not yet formed (visited count < total nodes):
Pop the edge with the minimum weight.
If the destination node of this edge is already visited, skip it.
Otherwise, mark the destination as visited, add the edge to the MST result, and add all outgoing edges from this new node to the priority queue.
Data Structures:
Graph Representation: Adjacency list is efficient. graph = {u: [(v, w), ...], ...}.
Visited: A set or boolean list.
Priority Queue:heapq module in Python.
Drafting the Code (Python):
python
import heapq
def prims_algorithm(graph, num_nodes):
# Initialization
mst = []
visited = set()
min_heap = [] # (weight, parent, current_node)
# Start from node 0
# (weight, source, destination) -> (0, -1, 0)
heapq.heappush(min_heap, (0, -1, 0))
while min_heap and len(visited) < num_nodes:
weight, parent, u = heapq.heappop(min_heap)
if u in visited:
continue
visited.add(u)
# Add to MST (ignore the dummy start edge)
if parent != -1:
mst.append((parent, u, weight))
# Explore neighbors
for v, w in graph[u]:
if v not in visited:
heapq.heappush(min_heap, (w, u, v))
return mst
Refining the Code:
The input format isn't specified. I should define a clear input (adjacency list) or an adjacency matrix. Adjacency list is better for sparse graphs. Let's stick with Adjacency List.
Edge case: Disconnected graph. The current logic handles it by just stopping if the heap empties before all nodes are visited, but I should probably check if len(visited) == num_nodes at the end to confirm an MST exists.
The tuple structure in heapq should be (weight, node_index). Since I want to reconstruct the path, storing the parent is useful. (weight, parent, current_node) works.
Alternative Implementation (Greedy approach using key array):
Maintain a key array initialized to infinity, except key[0] = 0.
Maintain parent array initialized to -1.
Maintain mstSet (boolean array).
Loop num_nodes times:
Find u not in mstSet with minimum key value. (This is slow O(V2) without a heap).
Mark u as visited.
Update key values of neighbors if weight < key[neighbor] and neighbor not in mstSet.
Decision: The Heap approach (O(Elog) is much better and more standard for production code. I will provide the Heap approach.
Finalizing the Python Code Structure:
Class-based or Functional? Functional is simpler for a snippet.
Pop (2, 0, 1). 1 visited. Add edge (0-1). Push neighbors of 1.
...
Wait, if I push neighbors regardless of visited status, the heap grows large.
Optimization: In the inner loop, check if v not in visitedbefore pushing? No, checking inside the pop is standard to avoid losing potential shorter paths to a node currently in the heap but not yet visited (though with Prim's, we only care about connecting the visited set to the unvisited set).
Actually, for Prim's, if a node v is not visited, we can push the edge connecting the current visited boundary to v. Even if v is already in the heap with a higher weight, the new lower weight will pop first. When the higher weight pops later, v will be in visited, so it gets skipped. This is correct.
Writing the explanation:
Explain Time Complexity (O(ElogV)).
Explain Space Complexity.
Provide an example usage.
Review against user prompt: "Write a program that implements Prim's minimum spanning tree algorithm."
The Python solution is solid.
I will also provide a C++ version just in case, as it's very common for students/competitions where speed matters. It makes the answer more complete.
(Self-Correction during C++ thought process): In C++, priority_queue puts the largest element at the top. I need to use greater or store negative weights to make it a min-heap.
Final Output Generation:
Python Implementation (Clean, readable).
C++ Implementation (Standard competitive programming style).
Explanation of logic.
Let's write the response.
Here are implementations of Prim's Algorithm in both Python and C++.
The Logic
Prim's algorithm is a greedy algorithm that finds a Minimum Spanning Tree (MST) for a weighted undirected graph. It works by:
Initializing the MST with a random starting node.
Finding the edge with the lowest weight that connects a node in the MST to a node not yet in the MST.
Adding that node to the MST.
Repeating steps 2-3 until all nodes are included.
Python Implementation
This solution uses an Adjacency List to represent the graph and a Min-Heap (Priority Queue) to efficiently select the next edge.
python
import heapq
def prim_mst(graph, start_node):
"""
Calculates the Minimum Spanning Tree (MST) of a graph using Prim's algorithm.
Args:
graph (dict): Adjacency list {node: [(neighbor, weight), ...]}
start_node: The node to start building the MST from.
Returns:
tuple: (total_weight, list_of_edges)
"""
# Set to keep track of visited nodes
visited = set()
# Min-heap to store edges: (weight, parent, current_node)
# We start with the start_node, which has no parent and 0 weight
min_heap = [(0, None, start_node)]
mst_edges = []
total_weight = 0
while min_heap and len(visited) < len(graph):
weight, parent, current_node = heapq.heappop(min_heap)
# If the node is already visited, skip it
if current_node in visited:
continue
# Mark node as visited
visited.add(current_node)
# If it's not the start node, add the edge to the MST
if parent is not None:
mst_edges.append((parent, current_node, weight))
total_weight += weight
# Add all edges from the current node to the heap
for neighbor, edge_weight in graph[current_node]:
if neighbor not in visited:
heapq.heappush(min_heap, (edge_weight, current_node, neighbor))
# Check if all nodes were visited (handles disconnected graphs)
if len(visited) != len(graph):
print("Warning: Graph is disconnected. MST could not be formed for all nodes.")
return total_weight, mst_edges
# --- Example Usage ---
if __name__ == "__main__":
# Graph representation: Adjacency List
# Keys are nodes, Values are lists of (neighbor, weight)
example_graph = {
'A': [('B', 2), ('D', 5)],
'B': [('A', 2), ('C', 3), ('D', 6)],
'C': [('B', 3), ('D', 4)],
'D': [('A', 5), ('B', 6), ('C', 4)]
}
start = 'A'
weight, edges = prim_mst(example_graph, start)
print(f"Total Weight of MST: {weight}")
print("Edges in MST:")
for u, v, w in edges:
print(f"{u} -- {v} (Weight: {w})")
C++ Implementation
This solution uses an Adjacency List (std::vector of std::pair), a Priority Queue, and a boolean visited array.
cpp
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
#include <functional>
// For larger graphs, use long long for weights
typedef long long ll;
struct Edge {
int to;
int weight;
};
// Comparator for the priority queue (Min-Heap)
// By default C++ priority_queue is a max-heap, so we use greater comparator
typedef std::pair<int, int> pii; // (weight, node)
void primMST(int num_nodes, std::vector<std::vector<Edge>>& adj, int start_node) {
// Vector to store the parent of each node in MST
std::vector<int> parent(num_nodes, -1);
// Vector to store the minimum weight to connect each node
std::vector<int> key(num_nodes, INT_MAX);
// Vector to keep track of visited nodes
std::vector<bool> visited(num_nodes, false);
// Priority Queue: stores (weight, node_index)
std::priority_queue<pii, std::vector<pii>, std::greater<pii>> pq;
// Initialize start node
key[start_node] = 0;
pq.push({0, start_node});
int total_weight = 0;
while (!pq.empty()) {
// Extract the node with the minimum weight edge
int u = pq.top().second;
int w = pq.top().first;
pq.pop();
// If already visited, skip (lazy deletion approach)
if (visited[u]) continue;
visited[u] = true;
total_weight += w;
// Iterate over all adjacent vertices
for (const Edge& edge : adj[u]) {
int v = edge.to;
int weight = edge.weight;
// If v is not visited and weight of (u,v) is smaller than current key of v
if (!visited[v] && weight < key[v]) {
key[v] = weight;
parent[v] = u;
pq.push({key[v], v});
}
}
}
// Output the MST
std::cout << "Total Weight of MST: " << total_weight << std::endl;
std::cout << "Edges in MST:" << std::endl;
// Start from 1 because node 0 is the root and has no parent
for (int i = 1; i < num_nodes; i++) {
if (parent[i] != -1) {
std::cout << parent[i] << " -- " << i << " (Weight: " << key[i] << ")" << std::endl;
}
}
}
int main() {
int V = 4; // Number of vertices
std::vector<std::vector<Edge>> graph(V);
// Helper to add edges (undirected)
auto addEdge = [&](int u, int v, int w) {
graph[u].push_back({v, w});
graph[v].push_back({u, w});
};
// Constructing the same graph as the Python example
// A=0, B=1, C=2, D=3
addEdge(0, 1, 2); // A-B
addEdge(0, 3, 5); // A-D
addEdge(1, 2, 3); // B-C
addEdge(1, 3, 6); // B-D
addEdge(2, 3, 4); // C-D
primMST(V, graph, 0);
return 0;
}
Complexity Analysis
Where V is the number of vertices and E is the number of edges.
Time Complexity:O(ElogV)
This assumes using a binary heap (or priority_queue) and an adjacency list. Each edge is pushed into the heap at most once, and popping from the heap takes logarithmic time.
Space Complexity:O(V+E)
Required to store the graph, the visited array, and the heap.