【问题标题】:Can someone detect error in this code to implement dijkstra's algorithm using python?有人可以检测到此代码中的错误以使用 python 实现 dijkstra 的算法吗?
【发布时间】:2017-08-31 18:51:39
【问题描述】:

我正在尝试实现 dijkstra 算法(在无向图上)以找到最短路径,我的代码是这样的。

注意:我没有使用堆/优先队列或任何东西,而是使用邻接列表、存储权重的字典和避免在循环/递归中永远循环的布尔列表。此外,该算法适用于大多数测试用例,但在此特定测试用例失败:https://ideone.com/iBAT0q

重要提示:图可以有多个从 v1 到 v2 的边(反之亦然),您必须使用最小权重。

import sys

sys.setrecursionlimit(10000)

def findMin(n):
    for i in x[n]:
        cost[n] = min(cost[n],cost[i]+w[(n,i)])
def dik(s):
    for i in x[s]:
        if done[i]:
            findMin(i)
            done[i] = False
            dik(i)
    return
q = int(input())
for _ in range(q):
    n,e = map(int,input().split())
    x = [[] for _ in range(n)]
    done =  [True]*n
    w = {}
    cost = [1000000000000000000]*n
    for k in range(e):
        i,j,c = map(int,input().split())
        x[i-1].append(j-1)
        x[j-1].append(i-1)
        try:                                       #Avoiding multiple edges
            w[(i-1,j-1)] = min(c,w[(i-1,j-1)])
            w[(j-1,i-1)] = w[(i-1,j-1)]
        except:
            try:
                w[(i-1,j-1)] = min(c,w[(j-1,i-1)])
                w[(j-1,i-1)] = w[(i-1,j-1)]
            except:
                w[(j-1,i-1)] = c
                w[(i-1,j-1)] = c
    src = int(input())-1
    #for i in sorted(w.keys()):
    #   print(i,w[i])
    done[src] = False
    cost[src] = 0
    dik(src)          #First iteration assigns possible minimum to all nodes
    done = [True]*n     
    dik(src)          #Second iteration to ensure they are minimum
    for val in cost:
        if val == 1000000000000000000:
            print(-1,end=' ')
            continue
        if val!=0:
            print(val,end=' ')
    print()

【问题讨论】:

    标签: python algorithm shortest-path dijkstra


    【解决方案1】:

    在第二遍中并不总能找到最佳值。如果您在示例中添加第三次传递,您会更接近预期结果,并且在第四次迭代之后,您就在那里。

    您可以迭代直到不再对成本数组进行更改:

    done[src] = False
    cost[src] = 0
    dik(src)
    
    while True:
        ocost = list(cost)          # copy for comparison
        done = [True]*n     
        dik(src)
        if cost == ocost:
            break
    

    【讨论】:

    • 感谢您浏览混乱的代码。但是,我注意到该算法本身不是 dijkstras,而是 bellman ford 的一些混乱和不完整的版本。我改变了我的方法并以另一种方式解决了它。谢谢! :)
    • 是的,这不是 Dijkstra 算法,但这个名称通常用于执行最短路径搜索的任何旧算法。很高兴您找到了解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 2011-06-10
    • 2018-11-29
    • 2021-05-05
    相关资源
    最近更新 更多