Dijkstra's algorithm code.

  • named after its discoverer, Dutch computer scientist Edsger Dijkstra, is a greedy algorithm that solves the single-source shortest path problem for a directed graph with nonnegative edge weights.
  • cost d[v] of the shortest path found so far between s and v.
    • Initially, this value is 0 for the source vertex s (d[s]=0),
    • Intially, infinity for all other vertices, representing the fact that we do not know any path leading to those vertices (d[v]=∞ for every v in V, except s).
  • Complexity O(V*V) with implementation here.....
    • For sparse graphs, that is, graphs with much less than V*V edges, Dijkstra's algorithm can be implemented more efficiently by storing the graph in the form of adjacency lists and using a binary heap or Fibonacci heap as a priority queue to implement the Extract-Min function. With a binary heap, the algorithm requires O((E+V)logV) time, and the Fibonacci heap improves this to O(E + VlogV).O((E+V)logV) time with heaps
  • Set S contains all vertices for which we know that the value d[v] is already the cost of the shortest path
  • Set Q contains all other vertices.
  • Algorithm Step: Set S starts empty, and in each step one vertex is moved from Q to S. This vertex is chosen as the vertex with lowest value of d[u]. When a vertex u is moved to S, the algorithm relaxes every outgoing edge (u,v).
    • relaxation is the process of looking at the vertex v and seeing if we the cost of d[u] + w(u,v) is less than the current d[v]. If this is less than the current d[v], we can replace the current value of d[v] with the new value.

PseudoCode

function Dijkstra(G, w, s)   
     for each vertex v in V[G]                        // Initializations   
           d[v] := infinity   
           previous[v] := undefined                   //this will represent
//chain-path back to s //from v that is minimum

d[s] := 0 // Distance from s to s S := empty set Q := V[G] // Set of all vertices while Q is not an empty set // The algorithm itself u := Extract_Min(Q) S := S union {u} for each edge (u,v) outgoing from u if d[u] + w(u,v) < d[v] // Relax (u,v) d[v] := d[u] + w(u,v) previous[v] := u function return u = Extract_Min(Q)      searches for ertex u in Q that has the smallest d[u] value. remove u from the set Q return u

 

 

© Lynne Grewe