Dijkstra's algorithm in python

后端 未结 11 1440
无人及你
无人及你 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:38

    This implementation use only array and heap ds.

    import heapq as hq
    import math
    
    def dijkstra(G, s):
        n = len(G)
        visited = [False]*n
        weights = [math.inf]*n
        path = [None]*n
        queue = []
        weights[s] = 0
        hq.heappush(queue, (0, s))
        while len(queue) > 0:
            g, u = hq.heappop(queue)
            visited[u] = True
            for v, w in G[u]:
                if not visited[v]:
                    f = g + w
                    if f < weights[v]:
                        weights[v] = f
                        path[v] = u
                        hq.heappush(queue, (f, v))
        return path, weights
    
    G = [[(1, 6), (3, 7)],
         [(2, 5), (3, 8), (4, -4)],
         [(1, -2), (4, 7)],
         [(2, -3), (4, 9)],
         [(0, 2)]]
    
    print(dijkstra(G, 0))
    

    I hope this could help someone, it's a little bit late.

提交回复
热议问题