コード例 #1
0
ファイル: dijkstra.py プロジェクト: MattRijk/data-structures
def singleSourceShortest(G, src):
    """
    Given graph G return dictionary of shortest paths to other vertices
    from vertex src. All vertices in G must be drawn from the range 0..n-1
    and src must also be from same range.
    """
    # Initialize dist[] matrix to be Infinity for all but src
    infinity = sys.maxsize
    n = 0
    dist = {}
    for v in range(len(G)):
        n += 1
        dist[v] = infinity

    dist[src] = 0

    # optimized construction for BinaryHeap
    pq = BinaryHeap(n, src, infinity)

    while not pq.isEmpty():
        u = pq.pop()
        for v,weight in G.neighbors(u):
            newLen = dist[u] + weight
            if newLen < dist[v]:
                pq.decreaseKey(v, newLen)
                dist[v] = newLen

    
    return dist
コード例 #2
0
def singleSourceShortest(G, src):
    """
    Given graph G return dictionary of shortest paths to other vertices
    from vertex src. All vertices in G must be drawn from the range 0..n-1
    and src must also be from same range.
    """
    # Initialize dist[] matrix to be Infinity for all but src
    infinity = sys.maxsize
    n = 0
    dist = {}
    for v in range(len(G)):
        n += 1
        dist[v] = infinity

    dist[src] = 0

    # optimized construction for BinaryHeap
    pq = BinaryHeap(n, src, infinity)

    while not pq.isEmpty():
        u = pq.pop()
        for v, weight in G.neighbors(u):
            newLen = dist[u] + weight
            if newLen < dist[v]:
                pq.decreaseKey(v, newLen)
                dist[v] = newLen

    return dist