Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit acf4baf

Browse files
committedOct 13, 2024·
kruskal_alog is coded
1 parent e9e7c96 commit acf4baf

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
 

‎graphs/kruskal_algo.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class DisjointSet:
2+
def __init__(self, n):
3+
self.parent = list(range(n))
4+
self.rank = [0] * n
5+
6+
def find(self, u):
7+
if self.parent[u] != u:
8+
self.parent[u] = self.find(self.parent[u])
9+
return self.parent[u]
10+
11+
def union(self, u, v):
12+
root_u = self.find(u)
13+
root_v = self.find(v)
14+
if root_u != root_v:
15+
# Union by rank
16+
if self.rank[root_u] > self.rank[root_v]:
17+
self.parent[root_v] = root_u
18+
elif self.rank[root_u] < self.rank[root_v]:
19+
self.parent[root_u] = root_v
20+
else:
21+
self.parent[root_v] = root_u
22+
self.rank[root_u] += 1
23+
24+
def kruskal_algorithm(vertices, edges):
25+
# Step 1: Sort edges based on weight
26+
edges.sort(key=lambda x: x[2])
27+
28+
# Step 2: Initialize Disjoint Set
29+
ds = DisjointSet(vertices)
30+
31+
mst = []
32+
mst_weight = 0
33+
34+
# Step 3: Iterate through sorted edges
35+
for u, v, weight in edges:
36+
# Check if adding this edge creates a cycle
37+
if ds.find(u) != ds.find(v):
38+
ds.union(u, v)
39+
mst.append((u, v, weight))
40+
mst_weight += weight
41+
42+
return mst, mst_weight
43+
44+
# Example usage:
45+
vertices = 4
46+
edges = [
47+
(0, 1, 10),
48+
(0, 2, 6),
49+
(0, 3, 5),
50+
(1, 3, 15),
51+
(2, 3, 4)
52+
]
53+
54+
mst, total_weight = kruskal_algorithm(vertices, edges)
55+
print("Edges in the MST:", mst)
56+
print("Total weight of the MST:", total_weight)

0 commit comments

Comments
 (0)
Please sign in to comment.