Skip to content

Commit 4a7234d

Browse files
authored
Create prims_minimum_spanning.py
code implemented for Prim's Algorithm to find minimum spanning tree. Although there was file named minimum_spanning_tree.py in graph section but contain only Kruskal Algorithm . Prim's Algo. was still missing
1 parent 6d1515d commit 4a7234d

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import heapq # for priority queue
2+
3+
# input number of nodes and edges in graph
4+
n, e = map (int,input().split())
5+
6+
# initializing empty graph as a dictionary (of the form {int:list})
7+
g = dict (zip ([i for i in range(1,n+1)],[[] for i in range(n)]))
8+
9+
# input graph data
10+
for i in range(e):
11+
a, b, c = map (int,input().split())
12+
g[a].append([c,b])
13+
g[b].append([c,a])
14+
15+
vis = []
16+
s = [[0,1]]
17+
prim = []
18+
mincost = 0
19+
20+
# prim's algo. to find weight of minimum spanning tree
21+
while (len(s)>0):
22+
v = heapq.heappop(s)
23+
x = v[1]
24+
if (x in vis):
25+
continue
26+
27+
mincost += v[0]
28+
prim.append(x)
29+
vis.append(x)
30+
31+
for j in g[x]:
32+
i = j[-1]
33+
if(i not in vis):
34+
heapq.heappush(s,j)
35+
36+
print(mincost)

0 commit comments

Comments
 (0)