Esempio n. 1
0
def dijkstra_heap(graph,source,stress = False):
    n_nodes = len(graph)
    Q = [True] * n_nodes
    dist = [MAX_INT] * n_nodes  #distance from source to v
    prev = [None] * n_nodes #previous node in optimal path
    dist[source] = 0
    S = Heap()

    for node,distance in enumerate(dist):
        S.insert((distance,node))

    while S.size != 0:
        #find vertex with minimum distance
        dist_u , u = S.pop() #instead of finding the minimum we just grab it. O(logn) vs O(n)
        Q[u] = False

        weights = graph[u]
        
        for v,edge in enumerate(weights):
            
            # can I find a way to relate this to the decrease priority?
            # yes. we need to iterate the heap itself and not the weight array

            
            if edge != MAX_INT and Q[v]: #v is in Q and is neighbor
                #we need some way of relating this to the heap
                
                alt = dist_u + edge #alternative path
                if alt < dist[v]: #alternative path is better
                    dist[v] = alt
                    prev[v] = u
                    S.decrease_priority(v,alt)
        if stress:
            #progress tracker - to be removed
            print(str(S.size)+'\r',end = '')
    return (dist,prev)