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 98a8aa0

Browse files
authoredOct 13, 2024··
Create krushkals_algorithm.py
1 parent e9e7c96 commit 98a8aa0

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
 

‎graphs/krushkals_algorithm.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
def find_parent(parent, node):
2+
if parent[node] == node:
3+
return node
4+
5+
parent[node] = find_parent(parent, parent[node])
6+
return parent[node]
7+
8+
def union_set(u, v, parent, rank):
9+
u = find_parent(parent, u)
10+
v = find_parent(parent, v)
11+
12+
if rank[u] < rank[v]:
13+
parent[u] = v
14+
else:
15+
parent[v] = u
16+
if rank[u] == rank[v]:
17+
rank[u] += 1
18+
19+
def make_set(n):
20+
parent = list(range(n))
21+
rank = [0] * n
22+
return parent, rank
23+
24+
def minimum_spanning_tree(edges, n):
25+
parent, rank = make_set(n)
26+
edges.sort(key=lambda x: x[2])
27+
28+
min_wt = 0
29+
30+
for u, v, w in edges:
31+
u_parent = find_parent(parent, u)
32+
v_parent = find_parent(parent, v)
33+
34+
if u_parent != v_parent:
35+
min_wt += w
36+
union_set(u_parent, v_parent, parent, rank)
37+
38+
return min_wt
39+
40+
def main():
41+
n = int(input("Enter the number of nodes: "))
42+
m = int(input("Enter the number of edges: "))
43+
44+
edges = []
45+
for _ in range(m):
46+
u, v, w = map(int, input().split())
47+
edges.append([u, v, w])
48+
49+
min_weight = minimum_spanning_tree(edges, n)
50+
51+
print(f"Weight of Kruskal's MST : {min_weight}")
52+
53+
if __name__ == "__main__":
54+
main()

0 commit comments

Comments
 (0)
Please sign in to comment.