Skip to content

Commit cf36a02

Browse files
authored
Create Kruskals_Algorithm.py
Added code for kruskal's algorithm. Kruskal's algorithm is a minimum spanning tree algorithm that finds the smallest set of edges that connects all vertices in a graph without forming cycles. Adding this to the "Graphs" folder.
1 parent 1571ef0 commit cf36a02

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

Graphs/Kruskals_Algorithm.py

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
#Kruskal's Algorithm seeks a minimum spanning tree using a greedy approach.
2+
#Greedy Approach: Selects edges in ascending order of weight, adding them to the MST if they avoid cycles.
3+
#Edge Sorting: Begins by sorting edges by weight in non-decreasing order.
4+
#Disjoint Set Data Structure: Utilizes Union-Find to efficiently manage connected components and prevent cycles.
5+
#Iterative Process: Adds edges to the MST iteratively, starting with the smallest weight edges, until V-1 edges are included (V is the number of vertices).
6+
#Safe Edge Selection: Ensures edges don't create cycles before adding them to the MST.
7+
#Efficiency: Kruskal's Algorithm has O(E log E) time complexity, making it suitable for sparse graphs.
8+
#Applications: Widely used in network design for road networks, electrical circuits, data center connections, and also in clustering and image segmentation.
9+
10+
class KruskalMST:
11+
def __init__(self, vertices):
12+
"""
13+
Initialize a KruskalMST object with the given number of vertices.
14+
15+
Args:
16+
vertices (int): The number of vertices in the graph.
17+
"""
18+
self.V = vertices
19+
self.graph = []
20+
21+
def add_edge(self, u, v, w):
22+
"""
23+
Add an edge to the graph.
24+
25+
Args:
26+
u (int): The source vertex.
27+
v (int): The destination vertex.
28+
w (int): The weight of the edge.
29+
"""
30+
self.graph.append([u, v, w])
31+
32+
def find(self, parent, i):
33+
"""
34+
Find the parent of a vertex using the union-find algorithm.
35+
36+
Args:
37+
parent (list): A list representing the parent of each vertex.
38+
i (int): The vertex to find the parent of.
39+
40+
Returns:
41+
int: The parent of the vertex.
42+
"""
43+
if parent[i] == i:
44+
return i
45+
return self.find(parent, parent[i])
46+
47+
def union(self, parent, rank, x, y):
48+
"""
49+
Union operation to merge two subsets into one.
50+
51+
Args:
52+
parent (list): A list representing the parent of each vertex.
53+
rank (list): A list representing the rank of each subset.
54+
x (int): The root of the first subset.
55+
y (int): The root of the second subset.
56+
"""
57+
root_x = self.find(parent, x)
58+
root_y = self.find(parent, y)
59+
60+
if rank[root_x] < rank[root_y]:
61+
parent[root_x] = root_y
62+
elif rank[root_x] > rank[root_y]:
63+
parent[root_y] = root_x
64+
else:
65+
parent[root_x] = root_y
66+
rank[root_y] += 1
67+
68+
def kruskal(self):
69+
"""
70+
Find the minimum spanning tree using Kruskal's algorithm.
71+
72+
Returns:
73+
list: A list of edges in the minimum spanning tree, represented as [u, v, w], where u and v are vertices
74+
and w is the edge weight.
75+
"""
76+
result = []
77+
self.graph = sorted(self.graph, key=lambda item: item[2])
78+
parent = [i for i in range(self.V)]
79+
rank = [0] * self.V
80+
i = 0
81+
e = 0
82+
while e < self.V - 1:
83+
u, v, w = self.graph[i]
84+
i += 1
85+
x = self.find(parent, u)
86+
y = self.find(parent, v)
87+
if x != y:
88+
e += 1
89+
result.append([u, v, w])
90+
self.union(parent, rank, x, y)
91+
return result
92+
93+
94+
# Example usage:
95+
g = KruskalMST(4)
96+
g.add_edge(0, 1, 10)
97+
g.add_edge(0, 2, 6)
98+
g.add_edge(0, 3, 5)
99+
g.add_edge(1, 3, 15)
100+
g.add_edge(2, 3, 4)
101+
mst = g.kruskal()
102+
print("Edges in Minimum Spanning Tree:")
103+
for u, v, w in mst:
104+
print(f"{u} - {v}: {w}")

0 commit comments

Comments
 (0)