【问题标题】:backwards Dijkstra's algorithm向后 Dijkstra 算法
【发布时间】:2020-04-20 22:01:08
【问题描述】:

我已经开始在python中实现反向Dijkstra算法了:

def backwardsDijkstra(g: DoubleDictGraph, s, t):
    q = PriorityQueue()
    dist = {}
    next = {}
    q.add(t, 0)
    dist[t] = 0
    found = False
    while not q.isEmpty() and not found:
        x = q.pop()
        for y in g.parseNin(x):
            if y not in dist.keys() or dist[x] + g.Cost(x, y) < dist[y]:
                dist[y] = dist[x] + g.Cost(x, y)
                q.add(y, dist[y])
                next[y] = x
        if x == t:
            found = True
    return dist[s], next

而且我不知道为什么它会在下一个图的第二次迭代中停止,例如:

5 7
0 1 5
0 2 20
1 2 10
1 3 30
2 3 5
2 4 20
3 4 10
(number of vertices, number of edges, (start,end,cost)

【问题讨论】:

  • 你为什么要检查目标? if x == t: found = True。你不应该检查来源吗?

标签: python graph shortest-path dijkstra


【解决方案1】:

你代码中的错误在这一行:

        if x == t:
            found = True

由于您从t(目标)开始,您应该寻找s(源)。目前,您正在为第一个候选者(即 t)打破循环。

【讨论】:

    猜你喜欢
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2011-06-27
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多