
158 views
Implementation of Kruskal?s Algorithm in Python
Kruskal’s algorithm is used to find the minimum spanning tree (MST) of a connected, undirected graph. Here’s an implementation of Kruskal’s algorithm in Python:
Python
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
def find_parent(self, parent, i):
if parent[i] == i:
return i
return self.find_parent(parent, parent[i])
def union(self, parent, rank, x, y):
x_root = self.find_parent(parent, x)
y_root = self.find_parent(parent, y)
if rank[x_root] < rank[y_root]:
parent[x_root] = y_root
elif rank[x_root] > rank[y_root]:
parent[y_root] = x_root
else:
parent[y_root] = x_root
rank[x_root] += 1
def kruskal(self):
result = []
i, e = 0, 0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = []
rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V - 1:
u, v, w = self.graph[i]
i += 1
x = self.find_parent(parent, u)
y = self.find_parent(parent, v)
if x != y:
e += 1
result.append([u, v, w])
self.union(parent, rank, x, y)
print("Edges in the Minimum Spanning Tree:")
for u, v, w in result:
print(f"{u} - {v} : {w}")
# Example usage
g = Graph(4)
g.add_edge(0, 1, 10)
g.add_edge(0, 2, 6)
g.add_edge(0, 3, 5)
g.add_edge(1, 3, 15)
g.add_edge(2, 3, 4)
g.kruskal()
In this implementation:
- The
Graph
class represents a graph withV
vertices. add_edge
is used to add edges to the graph, including the source vertexu
, destination vertexv
, and edge weightw
.find_parent
andunion
are helper functions for the disjoint-set data structure used to determine whether adding an edge creates a cycle.kruskal
is the main Kruskal’s algorithm function, which calculates the minimum spanning tree.
The provided example demonstrates how to create a Graph
object, add edges, and find the minimum spanning tree using Kruskal’s algorithm. You can adapt this code for your specific graph and edge-weight scenarios.