-
Notifications
You must be signed in to change notification settings - Fork 0
/
WeightedGraph.py
41 lines (33 loc) · 1013 Bytes
/
WeightedGraph.py
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
37
38
39
40
41
from collections import defaultdict
import heapq
counter_steps = 0
def create_spanning_tree(graph, starting_vertex):
global counter_steps
mst = defaultdict(set)
visited = set([starting_vertex])
edges = [
(cost, starting_vertex, to)
for to, cost in graph[starting_vertex].items()
]
heapq.heapify(edges)
while edges:
cost, frm, to = heapq.heappop(edges)
if to not in visited:
counter_steps += 1
visited.add(to)
mst[frm].add(to)
for to_next, cost in graph[to].items():
if to_next not in visited:
heapq.heappush(edges, (cost, to, to_next))
return mst
example_graph = {
'A': {'B': 2, 'C': 3},
'B': {'A': 2, 'C': 1, 'D': 1, 'E': 4},
'C': {'A': 3, 'B': 1, 'F': 5},
'D': {'B': 1, 'E': 1},
'E': {'B': 4, 'D': 1, 'F': 1},
'F': {'C': 5, 'E': 1, 'G': 1},
'G': {'F': 1},
}
print(create_spanning_tree(example_graph, 'A'))
print(counter_steps)