File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments