24. Spanning Tree Algorithms (Kruskal, Prim)
Description
Minimum Spanning Tree (MST) algorithms are used to find a tree that spans all vertices in a graph with the minimum total edge weight. For undirected graphs, there are several algorithms for finding a minimum spanning tree. The two most famous algorithms are Kruskal's Algorithm and Prim's Algorithm.
- Kruskal's Algorithm:
Kruskal's algorithm builds a minimum spanning tree by sorting edges by weight and adding them to the tree while avoiding cycles. It works efficiently with graphs represented as edge lists.
- Prim's Algorithm:
Prim's algorithm starts from a single vertex and sequentially adds edges with the minimum weight to the spanning tree, gradually expanding it. Prim's algorithm is efficient when working with graphs represented as adjacency lists or matrices.
1. Kruskal's Algorithm
Kruskal's algorithm is a greedy algorithm that builds a minimum spanning tree by sequentially adding edges with the smallest weight. An important part of the algorithm is the use of the Disjoint Set Union (DSU / Union-Find) data structure, which allows for efficient tracking and merging of connected components.
Steps of Kruskal's Algorithm:
- Sort graph edges by weight.
- Initialize an empty tree.
- Sequentially add edges to the tree if they do not form a cycle (checked via Union-Find).
- The algorithm completes when the tree covers all vertices.
Explanation & Example:
Given an edge-list representation, we:
- Sort edges by weight in non-decreasing order.
- Initialize a
UnionFindobject to track connected components. - Iterate through sorted edges and add each edge to the MST if its endpoint vertices belong to different components (verified and merged via
union). - Stop when all vertices are connected.
Example Output: Minimum Spanning Tree (Kruskal): [(0, 1, 1), (0, 2, 2), (2, 3, 4)]
Python Implementation (Kruskal's Algorithm):
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x]) # path compression
return self.parent[x]
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX != rootY:
# Union by rank
if self.rank[rootX] > self.rank[rootY]:
self.parent[rootY] = rootX
elif self.rank[rootX] < self.rank[rootY]:
self.parent[rootX] = rootY
else:
self.parent[rootY] = rootX
self.rank[rootX] += 1
return True
return False
def kruskal(n, edges):
# edges: list of edges in the format (weight, vertex1, vertex2)
uf = UnionFind(n)
mst = []
edges.sort() # Sort edges by weight
for weight, u, v in edges:
if uf.union(u, v):
mst.append((u, v, weight)) # Add edge to minimum spanning tree
return mst
# Example usage:
n = 4 # Number of vertices
edges = [
(1, 0, 1), # Edge with weight 1 between vertices 0 and 1
(3, 1, 2),
(2, 0, 2),
(4, 2, 3),
(5, 1, 3)
]
mst = kruskal(n, edges)
print("Minimum Spanning Tree (Kruskal):", mst)
2. Prim's Algorithm
Prim's algorithm works on a graph by growing a single MST component starting from an arbitrary vertex. It uses a minimum priority queue (min-heap) to pick the edge with the smallest weight that connects a vertex inside the tree to an unvisited vertex outside the tree at each step.
Steps of Prim's Algorithm:
- Start with an arbitrary vertex (e.g., vertex 0).
- Consider all edges connecting vertices inside the tree to vertices outside the tree, and select the edge with the minimum weight.
- Repeat step 2 until all vertices are included in the tree.
Explanation & Example:
- Start at vertex 0 and push
(0, 0)(weight, vertex) into a min-heap. - Pop the element with the lowest weight. If the vertex has not been visited, mark it as visited and record its edge.
- Push all outward edges from this vertex into the min-heap.
- Continue until all vertices are processed.
Example Output: Minimum Spanning Tree (Prim): [(0, 0), (1, 1), (2, 2), (3, 4)]
Python Implementation (Prim's Algorithm):
import heapq
def prim(n, graph):
# graph: adjacency list where graph[u] contains tuples of (weight, neighbor)
mst = []
visited = [False] * n
min_heap = [(0, 0)] # (edge_weight, vertex)
while min_heap:
weight, u = heapq.heappop(min_heap)
if visited[u]:
continue
visited[u] = True
mst.append((u, weight))
for weight, v in graph[u]:
if not visited[v]:
heapq.heappush(min_heap, (weight, v))
return mst
# Example usage:
n = 4 # Number of vertices
graph = {
0: [(1, 1), (2, 2)], # Vertex 0 connected to 1 (weight 1) and 2 (weight 2)
1: [(3, 3)], # Vertex 1 connected to 3 (weight 3)
2: [(4, 3)], # Vertex 2 connected to 3 (weight 4)
3: []
}
mst = prim(n, graph)
print("Minimum Spanning Tree (Prim):", mst)
Algorithm Complexity
- Kruskal's Algorithm:
- Time Complexity: O(E log E), where E is the number of edges, primarily due to sorting the edges.
- Space Complexity: O(V + E), where V is the number of vertices and E is the number of edges, required for storing edge lists and the Union-Find structure.
- Prim's Algorithm:
- Time Complexity: O(E log V), where E is the number of edges and V is the number of vertices, due to heap operations for edge insertion and extraction.
- Space Complexity: O(V + E), required to store the adjacency graph representation and priority queue.
Practical Applications
- Kruskal's Algorithm is generally faster for sparse graphs (graphs where the number of edges E is much smaller than V²).
- Prim's Algorithm performs better on dense graphs (graphs where E is close to V²).
Both algorithms are widely applied in network design, telecommunication layouts, circuit wiring, transportation route planning, and any problem involving minimum-cost connection structures.
All rights remain with the original author (Archiveskk). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me