[英]All Nodes shortest Paths
I am a new user to Python. 我是Python的新用户。 The following code is working for finding the shortest path from a source node, say B to all other nodes.
以下代码可用于查找从源节点(例如B)到所有其他节点的最短路径。 I am interested to find shortest distance from every node.ie, from A to all , from B to all, ..... from G to all.
我有兴趣找到每个节点之间的最短距离,即从A到所有,从B到所有,从G到所有。 Can some body help me please how to do it.
请问有什么身体可以帮助我。 Thank you.
谢谢。
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}}
unvisited = {node: None for node in nodes}
visited = {}
current = 'B'
currentDistance = 0
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(visited)
If you are trying to loop over all the nodes, you can do a loop over the initial value of current
. 如果尝试遍历所有节点,则可以对
current
的初始值进行遍历。 This will require minimal modification to your code: 这将需要对您的代码进行最少的修改:
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)
Basically, I made a loop over start
and set the initial current
to start
. 基本上,我对
start
进行了循环,并将初始current
设置为start
。 I also added a printout at the end to tell you which starting node the information is displayed for. 我还在末尾添加了打印输出,以告诉您显示该信息的起始节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.