-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprims.py
More file actions
36 lines (27 loc) · 851 Bytes
/
prims.py
File metadata and controls
36 lines (27 loc) · 851 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import heapq
def prims(graph , start):
visited= set()
total_cost= 0
MST= []
min_heap =[(0 , start , None)]
while min_heap:
weight , current , parent = heapq.heappop(min_heap)
if current in visited:
continue
total_cost += weight
visited.add(current)
if parent is not None:
MST.append((parent , current , weight))
for negh , wt in graph[current]:
if negh not in visited:
heapq.heappush(min_heap ,(wt , negh , current))
for u ,v ,w in MST:
print(f"{u}-{v}: {w}")
print(total_cost)
graph = {
'A': [('B', 1), ('C', 3)],
'B': [('A', 1), ('C', 1), ('D', 6)],
'C': [('A', 3), ('B', 1), ('D', 2)],
'D': [('B', 6), ('C', 2)],
}
prims(graph , 'A')