Dijkstra's algorithm in python

后端 未结 11 1449
无人及你
无人及你 2021-02-01 09:32

I am trying to implement Dijkstra\'s algorithm in python using arrays. This is my implementation.

def extract(Q, w):
    m=0
    minimum=w[0]
    for i in range(l         


        
11条回答
  •  庸人自扰
    2021-02-01 09:49

    Implementation based on CLRS 2nd Ed. Chapter 24.3

    d is deltas, p is predecessors

    import heapq
    
    def dijkstra(g, s, t):
    
        q = []
        d = {k: sys.maxint for k in g.keys()}
        p = {}
    
        d[s] = 0 
        heapq.heappush(q, (0, s))
    
        while q:
            last_w, curr_v = heapq.heappop(q)
            for n, n_w in g[curr_v]:
                cand_w = last_w + n_w # equivalent to d[curr_v] + n_w 
                # print d # uncomment to see how deltas are updated
                if cand_w < d[n]:
                    d[n] = cand_w
                    p[n] = curr_v
                    heapq.heappush(q, (cand_w, n))
    
        print "predecessors: ", p 
        print "delta: ", d 
        return d[t]
    
    def test():
    
        og = {}
        og["s"] = [("t", 10), ("y", 5)]
        og["t"] = [("y", 2), ("x", 1)]
        og["y"] = [("t", 3), ("x", 9), ("z", 2)]
        og["z"] = [("x", 6), ("s", 7)]
        og["x"] = [("z", 4)]
    
        assert dijkstra(og, "s", "x") == 9 
    
    
    if __name__ == "__main__":
        test()
    

    Implementation assumes all nodes are represented as keys. If say node(e.g "x" in the example above) was not defined as a key in the og, deltas d would be missing that key and check if cand_w < d[n] wouldn't work correctly.

提交回复
热议问题