遍历所有点的最短路径python_所有节点最短路径
如果您嘗試在所有節點上循環,可以對初始值current執行循環。這將需要對代碼進行最少的修改:nodes = ('A', 'B', 'C', 'D', 'E', 'F', 'G')
distances = {
'B': {'A': 5, 'D': 1, 'G': 2},
'A': {'B': 5, 'D': 3, 'E': 12, 'F' :5},
'D': {'B': 1, 'G': 1, 'E': 1, 'A': 3},
'G': {'B': 2, 'D': 1, 'C': 2},
'C': {'G': 2, 'E': 1, 'F': 16},
'E': {'A': 12, 'D': 1, 'C': 1, 'F': 2},
'F': {'A': 5, 'E': 2, 'C': 16}}
for start in nodes:
current = start
currentDistance = 0
unvisited = {node: None for node in nodes}
visited = {}
unvisited[current] = currentDistance
while True:
for neighbour, distance in distances[current].items():
if neighbour not in unvisited: continue
newDistance = currentDistance + distance
if unvisited[neighbour] is None or unvisited[neighbour] > newDistance:
unvisited[neighbour] = newDistance
visited[current] = currentDistance
del unvisited[current]
if not unvisited: break
candidates = [node for node in unvisited.items() if node[1]]
current, currentDistance = sorted(candidates, key = lambda x: x[1])[0]
print(' Shortest distances from %s ' % start)
print(visited)
基本上,我對start進行了一個循環,并將初始的current設置為start。我還在末尾添加了一個打印輸出,告訴您顯示信息的起始節點。在
總結
以上是生活随笔為你收集整理的遍历所有点的最短路径python_所有节点最短路径的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 两个不同无线路由器中继怎么设置双WIFI
- 下一篇: 如何了解自己电脑内存是否够用如何看电脑内