Skip to content

Commit 50e3372

Browse files
committed
无向图最小生成树prim算法
1 parent 5630e36 commit 50e3372

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

prim_algorithm.md

+13-3
Original file line numberDiff line numberDiff line change
@@ -36,16 +36,25 @@ edges = [ ("A", "B", 7),
3636
from heapq import *
3737

3838
def prim( vertexs, edges ):
39-
adjacent_vertex = defaultdict(list) #注意:defaultdict(list)必须以list做为变量,可以详细阅读:[collections.defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict)
40-
39+
adjacent_vertex = defaultdict(list)
40+
41+
"""
42+
注意:defaultdict(list)必须以list做为变量,可以详细阅读:[collections.defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict)
43+
"""
4144
for v1,v2,length in edges:
4245
adjacent_vertex[v1].append((length, v1, v2))
4346
adjacent_vertex[v2].append((length, v2, v1))
4447

4548
"""
4649
经过上述操作,将edges列表中各项归类成以某点为dictionary的key,其value则是其相邻的点以及边长。如下:
4750

48-
defaultdict(<type 'list'>, {'A': [(7, 'A', 'B'), (5, 'A', 'D')], 'C': [(8, 'C', 'B'), (5, 'C', 'E')], 'B': [(7, 'B', 'A'), (8, 'B', 'C'), (9, 'B', 'D'), (7, 'B', 'E')], 'E': [(7, 'E', 'B'), (5, 'E', 'C'), (15, 'E', 'D'), (8, 'E', 'F'), (9, 'E', 'G')], 'D': [(5, 'D', 'A'), (9, 'D', 'B'), (15, 'D', 'E'), (6, 'D', 'F')], 'G': [(9, 'G', 'E'), (11, 'G', 'F')], 'F': [(6, 'F', 'D'), (8, 'F', 'E'), (11, 'F', 'G')]})
51+
defaultdict(<type 'list'>, {'A': [(7, 'A', 'B'), (5, 'A', 'D')],
52+
'C': [(8, 'C', 'B'), (5, 'C', 'E')],
53+
'B': [(7, 'B', 'A'), (8, 'B', 'C'), (9, 'B', 'D'), (7, 'B', 'E')],
54+
'E': [(7, 'E', 'B'), (5, 'E', 'C'), (15, 'E', 'D'), (8, 'E', 'F'), (9, 'E', 'G')],
55+
'D': [(5, 'D', 'A'), (9, 'D', 'B'), (15, 'D', 'E'), (6, 'D', 'F')],
56+
'G': [(9, 'G', 'E'), (11, 'G', 'F')],
57+
'F': [(6, 'F', 'D'), (8, 'F', 'E'), (11, 'F', 'G')]})
4958

5059
"""
5160

@@ -103,6 +112,7 @@ edges = [ ("A", "B", 7),
103112
##运行结果
104113

105114
edges: [('A', 'B', 7), ('A', 'D', 5), ('B', 'C', 8), ('B', 'D', 9), ('B', 'E', 7), ('C', 'E', 5), ('D', 'E', 15), ('D', 'F', 6), ('E', 'F', 8), ('E', 'G', 9), ('F', 'G', 11)]
115+
106116
prim: [('A', 'D', 5), ('D', 'F', 6), ('A', 'B', 7), ('B', 'E', 7), ('E', 'C', 5), ('E', 'G', 9)]
107117

108118

0 commit comments

Comments
 (0)