【问题标题】:All Nodes shortest Paths所有节点最短路径
【发布时间】:2016-07-18 17:37:12
【问题描述】:

我是 Python 的新用户。以下代码用于查找从源节点(例如 B)到所有其他节点的最短路径。我有兴趣找到每个节点的最短距离。即从 A 到 all ,从 B 到 all ,......从 G 到 all 。有人可以帮我请教怎么做。谢谢。

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)

【问题讨论】:

  • 以每个节点为起始节点运行算法。
  • 感谢您的回复。但这是一个手动过程。我想以循环方式进行,但不知道如何添加该循环。谢谢。

标签: python dijkstra


【解决方案1】:

如果您尝试循环遍历所有节点,您可以循环遍历 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。我还在末尾添加了一个打印输出,以告诉您显示信息的起始节点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    相关资源
    最近更新 更多