Skip to main content

Prim's Algorithm for Minimum Spanning Tree

Introduction​

Prim's Algorithm is a greedy algorithm used for finding the Minimum Spanning Tree (MST) of a weighted undirected graph. The MST is a subset of the graph's edges that connects all vertices together without cycles and with the minimum possible total edge weight.

Key Concepts​

  • Minimum Spanning Tree (MST): A tree that spans all the vertices of the graph with the minimum total edge weight.
  • Greedy Algorithm: At each step, the algorithm selects the edge with the smallest weight that connects a vertex in the MST to a vertex outside the MST.

Steps​

  1. Initialize a tree with a single vertex, chosen arbitrarily from the graph.
  2. Grow the tree by one edge: select the edge with the smallest weight that connects a vertex in the tree to a vertex outside the tree.
  3. Repeat step 2 until all vertices are included in the tree.

Pseudocode​

Here’s the pseudocode for Prim's Algorithm:

function prim(graph, start):
initialize a priority queue (min-heap) and a list for the MST
add start vertex to the MST
for each edge from the start vertex, add edge to the priority queue

while the priority queue is not empty:
edge = extract-min from the priority queue
if the edge connects a vertex in the MST to a vertex outside the MST:
add edge to the MST
add the new vertex to the MST
for each edge from the new vertex, add edge to the priority queue

return MST
import heapq

def prim(graph, start):
mst = []
visited = set([start])
edges = [(cost, start, to) for to, cost in graph[start].items()]
heapq.heapify(edges)

while edges:
cost, frm, to = heapq.heappop(edges)
if to not in visited:
visited.add(to)
mst.append((frm, to, cost))
for to_next, cost in graph[to].items():
if to_next not in visited:
heapq.heappush(edges, (cost, to, to_next))

return mst

# Example usage
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 3, 'D': 2},
'C': {'A': 4, 'B': 3, 'D': 5},
'D': {'B': 2, 'C': 5}
}

mst = prim(graph, 'A')
print(mst) # Output: [('A', 'B', 1), ('B', 'D', 2), ('B', 'C', 3)]

Example​

Consider a weighted undirected graph with vertices and edges:

graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 3, 'D': 2},
'C': {'A': 4, 'B': 3, 'D': 5},
'D': {'B': 2, 'C': 5}
}
  1. Start with vertex 'A'.
  2. The edge with the smallest weight from 'A' is ('A', 'B', 1), add it to the MST.
  3. The next smallest edge is ('B', 'D', 2), add it to the MST.
  4. Finally, add edge ('B', 'C', 3) to the MST.

The MST contains the edges: [('A', 'B', 1), ('B', 'D', 2), ('B', 'C', 3)].

Conclusion​

Prim's Algorithm is an efficient method for finding the Minimum Spanning Tree of a weighted undirected graph. It operates in O(ElogV)O(E log V) time complexity using a priority queue, making it suitable for large graphs. Understanding and implementing this algorithm is fundamental for solving various network design problems and optimizing connectivity.