File tree Expand file tree Collapse file tree
AlgorithmDiagram9787115447630/chapter07 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ """ 狄克斯特拉算法 """
2+
3+ """ 从起点到终点,找到耗时最短的路径:
4+ 01 各个节点之间的关系图:
5+
6+ 6 1
7+ /--------> A --------\
8+ / ^ \
9+ / | \_
10+ S(起点) | 3 |----> F(终点)
11+ \ | /
12+ \ | /
13+ \--------> B --------/
14+ 2 5
15+
16+ """
17+
18+
19+ # 搜索最短路径
20+ def search (graph , costs , parents , processed ):
21+ node = find_lowest_cost_node (costs , processed ) # 在未处理的节点中找出开销最小的节点
22+ while node is not None : # 这个 while 循环在所有节点都被处理过后结束
23+ cost = costs [node ]
24+ neighbors = graph [node ]
25+ for n in neighbors .keys (): # 遍历当前节点的所有邻居
26+ new_cost = cost + neighbors [n ]
27+ if costs [n ] > new_cost : # 如果经当前节点前往该邻居节点更近,
28+ costs [n ] = new_cost # 就更新该邻居的开销
29+ parents [n ] = node # 同时将该邻居的父节点设置为当前节点
30+ processed .append (node ) # 将当前节点标记为处理过
31+ node = find_lowest_cost_node (costs , processed ) # 找出接下来要处理的节点,并循环
32+ print ("最短路径信息:" )
33+ print (costs )
34+ print ("父节点信息:" )
35+ print (parents )
36+
37+
38+ # 找出开销最小的节点
39+ def find_lowest_cost_node (costs , processed ):
40+ lowest_cost = float ("inf" )
41+ lowest_cost_node = None
42+ for node in costs : # 遍历所有节点
43+ cost = costs [node ]
44+ if cost < lowest_cost and node not in processed : # 如果当前节点的开销更低且未处理过
45+ lowest_cost = cost
46+ lowest_cost_node = node
47+ return lowest_cost_node
48+
49+
50+ # 初始化图的信息,使用三张散列表 graph, costs, parents 和一个数组 processed
51+
52+ # 节点关系表 graph
53+ graph = {}
54+ graph ["start" ] = {}
55+ graph ["start" ]["a" ] = 6
56+ graph ["start" ]["b" ] = 2
57+ graph ["a" ] = {}
58+ graph ["a" ]["fin" ] = 1
59+ graph ["b" ] = {}
60+ graph ["b" ]["a" ] = 3
61+ graph ["b" ]["fin" ] = 5
62+ graph ["fin" ] = {}
63+
64+ # 节点开销表
65+ infinity = float ("inf" )
66+ costs = {}
67+ costs ["a" ] = 6
68+ costs ["b" ] = 2
69+ costs ["fin" ] = infinity
70+
71+ # 节点的父节点关系表
72+ parents = {}
73+ parents ["a" ] = "start"
74+ parents ["b" ] = "start"
75+ parents ["fin" ] = None
76+
77+ # 处理过的节点
78+ processed = []
79+
80+ search (graph , costs , parents , processed )
You can’t perform that action at this time.
0 commit comments