Dijkstra's algorithm in python

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

    This is not my answer - my prof did it much more efficiently than my attempt. Here is his approach, obviously using helper-functions for the repetitive tasks

    def dijkstra(graph, source):
    
        vertices, edges = graph
        dist = dict()
        previous = dict()
    
        for vertex in vertices:
            dist[vertex] = float("inf")
            previous[vertex] = None
    
        dist[source] = 0
        Q = set(vertices)
    
        while len(Q) > 0:
            u = minimum_distance(dist, Q)
            print('Currently considering', u, 'with a distance of', dist[u])
            Q.remove(u)
    
            if dist[u] == float('inf'):
                break
    
            n = get_neighbours(graph, u)
            for vertex in n:
                alt = dist[u] + dist_between(graph, u, vertex)
                if alt < dist[vertex]:
                    dist[vertex] = alt
                    previous[vertex] = u
    
        return previous
    

    Given a graph

    ({'A', 'B', 'C', 'D'}, {('A', 'B', 5), ('B', 'A', 5), ('B', 'C', 10), ('B', 'D', 6), ('C', 'D', 2), ('D', 'C', 2)})

    the command print(dijkstra(graph, 'A') yields

    Currently considering A with a distance of 0

    Currently considering B with a distance of 5

    Currently considering D with a distance of 11

    Currently considering C with a distance of 13

    id est:

    {'C': 'D', 'D': 'B', 'A': None, 'B': 'A'} => in random order

提交回复
热议问题