Skip to content

Commit 6d193cf

Browse files
authored
Merge pull request himanshu-03#84 from surya-mu/main
add: Prim's Algorithm to Find MST.
2 parents 237e44d + bd9ee82 commit 6d193cf

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
//Prim's Algo to calculate the minimum spanning tree with user-input, using the Fibonacci Heap Method.
2+
3+
import sys
4+
import heapq
5+
6+
class UniqueGraph:
7+
def __init(self, vertices_count):
8+
self.V = vertices_count
9+
self.edges = [[] for _ in range(vertices_count)]
10+
11+
def find_min_edge(self, key_values, mst_set):
12+
min_value = sys.maxsize
13+
min_index = 0
14+
15+
for vertex in range(self.V):
16+
if key_values[vertex] < min_value and not mst_set[vertex]:
17+
min_value = key_values[vertex]
18+
min_index = vertex
19+
20+
return min_index
21+
22+
def find_minimum_spanning_tree(self):
23+
parents = [None] * self.V
24+
key_values = [sys.maxsize] * self.V
25+
key_values[0] = 0
26+
mst_set = [False] * self.V
27+
28+
parents[0] = -1
29+
min_heap = [(0, 0)]
30+
31+
while min_heap:
32+
current_value, current_vertex = heapq.heappop(min_heap)
33+
mst_set[current_vertex] = True
34+
35+
for edge in self.edges[current_vertex]:
36+
adjacent_vertex, weight = edge
37+
if not mst_set[adjacent_vertex] and key_values[adjacent_vertex] > weight:
38+
key_values[adjacent_vertex] = weight
39+
parents[adjacent_vertex] = current_vertex
40+
heapq.heappush(min_heap, (key_values[adjacent_vertex], adjacent_vertex))
41+
42+
self.print_minimum_spanning_tree(parents, key_values)
43+
44+
def print_minimum_spanning_tree(self, parents, key_values):
45+
print("Edge \tWeight")
46+
for vertex in range(1, self.V):
47+
print(f"{parents[vertex]} - {vertex}\t{key_values[vertex]}")
48+
49+
# Input the graph from the user
50+
V = int(input("Enter the number of vertices: "))
51+
g = UniqueGraph(V)
52+
print("Enter the edges and their weights (e.g., '1 2 3' means an edge from vertex 1 to vertex 2 with weight 3):")
53+
54+
for _ in range(V - 1):
55+
u, v, w = map(int, input().split())
56+
g.edges[u].append((v, w))
57+
g.edges[v].append((u, w))
58+
59+
g.find_minimum_spanning_tree()

0 commit comments

Comments
 (0)