forked from muzixing/graph_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprim.py
More file actions
37 lines (30 loc) · 1.01 KB
/
prim.py
File metadata and controls
37 lines (30 loc) · 1.01 KB
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
def prim(graph, root):
assert type(graph)==dict
nodes = graph.keys()
nodes.remove(root)
visited = [root]
path = []
next = None
while nodes:
distance = float('inf')
for s in visited:
for d in graph[s]:
if d in visited or s == d:
continue
if graph[s][d] < distance:
distance = graph[s][d]
pre = s
next = d
path.append((pre, next))
visited.append(next)
nodes.remove(next)
return path
if __name__ == '__main__':
graph_dict = { "s1":{"s1": 0, "s2": 2, "s10": 3, "s12": 4, "s5":3},
"s2":{"s1": 1, "s2": 0, "s10": 4, "s12": 2, "s5":2},
"s10":{"s1": 2, "s2": 6, "s10": 0, "s12":3, "s5":4},
"s12":{"s1": 3, "s2": 5, "s10": 2, "s12":0,"s5":2},
"s5":{"s1": 3, "s2": 5, "s10": 2, "s12":4,"s5":0},
}
path = prim(graph_dict, 's12')
print path