Shortest Path

Dijkstra’s algorithm

Procedure DIJKSTRA(G, s) 

Inputs: 
    * G: a directed graph containing a set V of n vertices and a set E of m 
        directed edges with nonnegative weights. 
    * s: a source vertex in V. 
    
Result: For each non-source vertex v in V, shortest[v] is the weight sp(s, v) 
        of a shortest path from s to v and pred[v] is the vertex preceding v 
        on some shortest path. For the source vertex s, shortest[s] = 0 and 
        pred[s] = NULL. If there is no path from s to v, then shortest[v] = ∞ 
        and pred[v] = NULL. 
        
1. Set shortest[v] to ∞ for each vertex v except s, set shortest[s] to 0, 
        and set pred[v] to NULL for each vertex v. 
2. Set Q to contain all vertices.
3. While Q is not empty, do the following:  
        A. Find the vertex u in set Q with the lowest shortest value and 
                remove it from Q. 
        B. For each vertex v adjacent to u:  
                i. Call RELAX(u, v).
Procedure RELAX(u, v) 
    Inputs: u, v: vertices such that there is an edge (u, v). 
    Result: The value of shortest[v] might decrease, and if it does, 
            then pred[v] becomes u. 
        
    1. If shortest[u] + weight(u, v) < shortest[v], 
            then set shortest[v] to shortest[u] + weight(u, v) 
            and set pred[v] to u.
def graph_distance(g: object, s: object) -> object:
    '''
    Dijkstra Algorithm -> find the shortest path between two vertices
    :param g: a square matrix
    :param s: start index
    :return: shortest path
    '''
    n = len(g)
    distances = [float('Inf')] * n
    queue = set(range(n))

    # initial node has a distance of 0
    distances[s] = 0

    while len(queue):
        # find the element with min distance
        min_index = -1
        for i in queue:
            if min_index == -1 or distances[i] < distances[min_index]:
                min_index = i

        # remove min_index from the queue
        queue.remove(min_index)

        # look at all of the unvisited neighbours
        for next_index in range(n):
            weight = g[min_index][next_index]
            if weight != -1:
                # re-assess distance
                other_dist = distances[min_index] + weight

                if other_dist < distances[next_index]:
                    distances[next_index] = other_dist

    return distances


g = [[-1,  3,  2],
     [ 2, -1,  0],
     [-1,  0, -1]]
s = 0
print(graph_distance(g, s))  # [0, 2, 2]

Simple array implementation

Procedure DIJKSTRA(G, s) 
Inputs and Result: Same as before. 
    1. Set shortest[v] to ∞ for each vertex v except s, set shortest[s] to 0, 
        and set pred[v] to NULL for each vertex v.

    2. Make Q an empty priority-queue. 
    3. For each vertex v:  
        A. Call INSERT(Q, v). 
    4. While Q is not empty, do the following:  
        A. Call EXTRACT-MIN(Q) and set u to hold the returned vertex. 
        B. For each vertex v adjacent to u:  
            i. Call RELAX(u, v). 
            ii. If the call to RELAX(u, v) decreased the value of shortest[v], 
                then call DECREASE-KEY(Q, v).

Operations:

  • INSERT (Q, v) inserts vertex v into set Q. (Dijkstra’s algorithm calls INSERT n times.)

  • EXTRACT-MIN (Q) removes the vertex in Q with the minimum shortest value and returns this vertex to its caller. (Dijkstra’s algorithm calls EXTRACT-MIN n times.)

  • DECREASE-KEY (Q, v) performs whatever bookkeeping is necessary in Q to record that shortest[v] was decreased by a call of RELAX. (Dijkstra’s algorithm calls DECREASE-KEY up to m times.)

Binary heap implementation

A binary heap organizes data as a binary tree stored in an array. A binary tree is a type of graph, but we refer to its vertices as nodes, the edges are undirected, and each node has 0, 1, or 2 nodes below it, which are its children. On the left side of the figure on the next page is an example of a binary tree, with the nodes numbered. Nodes with no children, such as nodes 6 through 10, are leaves.

A binary heap is a binary tree with three additional properties. First, the tree is completely filled on all levels, except possibly the lowest, which is filled from the left up to a point. Second, each node contains a key, shown inside each node in the figure. Third, the keys obey the heap property: the key of each node is less than or equal to the keys of its children. The binary tree in the figure is also a binary heap.

We can store a binary heap in an array, as shown on the right in the figure. Because of the heap property, the node with the minimum key must always be at position 1. The children of the node at position i are at positions 2i2i and 2i+12i + 1, and the node above the node at position i—its parent—is at position i/2\lfloor i / 2 \rfloor . It is easy to navigate up and down within a binary heap when we store it in an array.

Procedure HEAPSORT(A, n) 

Inputs: 
    * A: an array. 
    * n: the number of elements in A to sort. 
    
Output: An array B containing the elements of A, sorted. 

1. Build a binary heap Q from the elements of A. 
2. Let B[1 . . n] be a new array. 
3. For i = 1 to n:  
    A. Call EXTRACT-MIN(Q) and set B[i] to the value returned. 
4. Return the B array.

The Bellman-Ford algorithm

Procedure BELLMAN-FORD(G, s)

Inputs:
    * G: a directed graph containing a set V of n vertices and 
            a set E of m directed edges with arbitrary weights. 
    * s: a source vertex in V. 
    
Result: Same as DIJKSTRA. 
1. Set shortest[v] to ∞ for each vertex v except s, set shortest[s] to 0, 
    and set pred[v] to NULL for each vertex v. 
2. For i = 1 to n − 1:  
    A. For each edge (u, v) in E:  
        i. Call RELAX(u, v).
Procedure FIND-NEGATIVE-WEIGHT-CYCLE(G) 

Input: 
    G: a directed graph containing a set V of n vertices and 
        a set E of m directed edges with arbitrary weights on 
        which the BELLMAN-FORD procedure has already been run. 
        
Output: Either a list of vertices in a negative-weight cycle, in order, 
        or an empty list if the graph has no negative-weight cycles. 
        
1. Go through all edges to find any edge (u, v) such that 
    shortest[u] + weight(u, v) < shortest[v]. 
2. If no such edge exists, then return an empty list. 
3. Otherwise (there is some edge (u, v) for which 
    shortest[u] + weight(u, v) < shortest[v]), do the following:  
    A. Let visited be a new array with one element for each vertex. 
        Set all elements of visited to FALSE. 
    B. Set x to v. 
    C. While visited[x] is FALSE, do the following:  
        i. Set visited[x] to TRUE. 
        ii. Set x to pred[x] 
    D. At this point, we know that x is a vertex on a negative-weight cycle. 
        Set v to pred[x]. 
    E. Create a list cycle of vertices initially containing just x. 
    F. While v is not x, do the following:  
        i. Insert vertex v at the beginning of cycle. 
        ii. Set v to pred[v]. 
    G. Return cycle.

The Floyd-Warshall algorithm

Now suppose that you want to find a shortest path from every vertex to every vertex. That’s the all-pairs shortest-paths problem.

The classic example of all-pairs shortest paths—which I have seen several authors refer to—is the table that you see in a road atlas giving distances between several cities. You find the row for one city, you find the column for the other city, and the distance between them lies at the intersection of the row and column.

Procedure FLOYD-WARSHALL(G) 

Input: G: a graph represented by a weighted adjacency matrix W with n rows and 
    n columns (one row and one column per vertex). The entry in row u and 
    column v, denoted wuv, is the weight of edge (u, v) if this edge is present 
    in G, and it is ∞ otherwise. 

Output: For each pair of vertices u and v, the value of shortest[u, v, n] 
    contains the weight of a shortest path from u to v, and pred[u, v, n] 
    is the predecessor vertex of v on a shortest path from u. 
    
1. Let shortest and pred be new n × n × (n + 1) arrays. 
2. For each u and v from 1 to n:  
    A. Set shortest[u, v, 0] to wuv. 
    B. If (u, v) is an edge in G, then set pred[u, v, 0] to u. 
        Otherwise, set pred[u, v, 0] to NULL. 
3. For x = 1 to n:  
    A. For u = 1 to n:  
        i. For v = 1 to n:  
            a. If shortest[u, v, x] < shortest[u, x, x − 1] + 
                shortest[x, v, x − 1], then set shortest[u, v, x] to 
                shortest[u, x, x − 1] + shortest[x, v, x − 1] and set 
                pred[u, v, x] to pred[x, v, x − 1]. 
            b. Otherwise, set shortest[u, v, x] to shortest[u, v, x − 1] and set 
                pred[u, v, x] to pred[u, v, x − 1].
4. Return the shortest and pred arrays.

Last updated