Skip to content

Commit d7ceafc

Browse files
authored
Update prims_minimum_spanning.py
function and sample test cases added
1 parent 4a7234d commit d7ceafc

File tree

1 file changed

+59
-31
lines changed

1 file changed

+59
-31
lines changed
Lines changed: 59 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,64 @@
11
import heapq # for priority queue
22

3-
# input number of nodes and edges in graph
4-
n, e = map (int,input().split())
3+
# prim's algo. to find weight of minimum spanning tree
4+
def prims(graph):
5+
vis=[]
6+
s=[[0,1]]
7+
prim = []
8+
mincost=0
9+
10+
while(len(s)>0):
11+
v=heapq.heappop(s)
12+
x=v[1]
13+
if(x in vis):
14+
continue
515

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)]))
16+
mincost += v[0]
17+
prim.append(x)
18+
vis.append(x)
819

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
20+
for j in g[x]:
21+
i=j[-1]
22+
if(i not in vis):
23+
heapq.heappush(s,j)
1924

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)
25+
return mincost
26+
27+
28+
29+
if __name__=="__main__":
30+
31+
# input number of nodes and edges in graph
32+
n,e = map(int,input().split())
33+
34+
# initializing empty graph as a dictionary (of the form {int:list})
35+
g=dict(zip([i for i in range(1,n+1)],[[] for i in range(n)]))
36+
37+
# input graph data
38+
for i in range(e):
39+
a,b,c=map(int,input().split())
40+
g[a].append([c,b])
41+
g[b].append([c,a])
42+
43+
# print weight of minimum spanning tree
44+
print(prims(g))
45+
46+
''' tests-
47+
Input : 4 5
48+
1 2 7
49+
1 4 6
50+
2 4 9
51+
4 3 8
52+
2 3 6
53+
Output : 19
54+
55+
56+
Input : 5 6
57+
1 2 3
58+
1 3 8
59+
2 4 5
60+
3 4 2
61+
3 5 4
62+
4 5 6
63+
Output : 14
64+
'''

0 commit comments

Comments
 (0)