Ejemplo n.º 1
0
def singleSourceShortestPath(graph, s):
    """Compute and return (dist, pred) matrices of computation"""

    pq = BHeap(len(graph))
    dist = {}
    pred = {}

    for v in graph:
        dist[v] = sys.maxint
        pred[v] = None
    dist[s] = 0

    for v in graph:
        pq.insert(v, dist[v])

    while not pq.isEmpty():
        u = pq.smallest()
        for v in graph[u]:
            wt = graph[u][v]
            newLen = dist[u] + wt

            if newLen < dist[v]:
                pq.decreaseKey(v, newLen)
                dist[v] = newLen
                pred[v] = u

    return (dist, pred)
Ejemplo n.º 2
0
def computeMST(graph):
    """Return set of edges that forms MST starting search from s"""

    key = {}
    pred = {}
    inqueue = {}
    for v in graph:
        key[v] = sys.maxint
        pred[v] = None

    # choose any vertex to start from. Use last from previous loop
    key[v] = 0
    pq = BHeap(len(graph))
    for v in graph:
        pq.insert(v, key[v])
        inqueue[v] = True

    while not pq.isEmpty():
        u = pq.smallest()
        inqueue[u] = False
        
        for v in graph[u]:
            if inqueue[v]:
                wt = graph[u][v]
                if wt < key[v]:
                    pred[v] = u
                    key[v] = wt
                    pq.decreaseKey(v, wt)

    return pred
Ejemplo n.º 3
0
def computeMST(graph):
    """Return set of edges that forms MST starting search from s"""

    key = {}
    pred = {}
    inqueue = {}
    for v in graph:
        key[v] = sys.maxint
        pred[v] = None

    # choose any vertex to start from. Use last from previous loop
    key[v] = 0
    pq = BHeap(len(graph))
    for v in graph:
        pq.insert(v, key[v])
        inqueue[v] = True

    while not pq.isEmpty():
        u = pq.smallest()
        inqueue[u] = False

        for v in graph[u]:
            if inqueue[v]:
                wt = graph[u][v]
                if wt < key[v]:
                    pred[v] = u
                    key[v] = wt
                    pq.decreaseKey(v, wt)

    return pred
Ejemplo n.º 4
0
def singleSourceShortestPath(graph, s):
    """Compute and return (dist, pred) matrices of computation"""

    pq = BHeap(len(graph))
    dist = {}
    pred = {}
    
    for v in graph:
        dist[v] = sys.maxint
        pred[v] = None
    dist[s] = 0

    for v in graph:
        pq.insert(v, dist[v])

    while not pq.isEmpty():
        u = pq.smallest()
        for v in graph[u]:
            wt = graph[u][v]
            newLen = dist[u] + wt

            if newLen < dist[v]:
                pq.decreaseKey(v, newLen)
                dist[v] = newLen
                pred[v] = u
                
    return (dist, pred)