Skip to content

Commit 04c83ef

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent acf4baf commit 04c83ef

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed

graphs/kruskal_algo.py

+8-13
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@ def find(self, u):
1010

1111
def union(self, u, v):
1212
root_u = self.find(u)
13-
root_v = self.find(v)
14-
if root_u != root_v:
13+
if root_u != (root_v := self.find(v)):
1514
# Union by rank
1615
if self.rank[root_u] > self.rank[root_v]:
1716
self.parent[root_v] = root_u
@@ -21,35 +20,31 @@ def union(self, u, v):
2120
self.parent[root_v] = root_u
2221
self.rank[root_u] += 1
2322

23+
2424
def kruskal_algorithm(vertices, edges):
2525
# Step 1: Sort edges based on weight
2626
edges.sort(key=lambda x: x[2])
27-
27+
2828
# Step 2: Initialize Disjoint Set
2929
ds = DisjointSet(vertices)
30-
30+
3131
mst = []
3232
mst_weight = 0
33-
33+
3434
# Step 3: Iterate through sorted edges
3535
for u, v, weight in edges:
3636
# Check if adding this edge creates a cycle
3737
if ds.find(u) != ds.find(v):
3838
ds.union(u, v)
3939
mst.append((u, v, weight))
4040
mst_weight += weight
41-
41+
4242
return mst, mst_weight
4343

44+
4445
# Example usage:
4546
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-
]
47+
edges = [(0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4)]
5348

5449
mst, total_weight = kruskal_algorithm(vertices, edges)
5550
print("Edges in the MST:", mst)

0 commit comments

Comments
 (0)