Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra is a graph search algorithm that solves the single-source shortest path problem for a connected graph with nonnegative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms.
For a given source vertex (node) in the connected graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used for finding costs of shortest paths from a single vertex to a single destination vertex by stopping the algorithm once the shortest path to the destination vertex has been determined. For example, if the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably IS-IS and OSPF (Open Shortest Path First).
Pseudocode :
function Dijkstra(Graph, source):
for each vertex v in Graph: // Initializations
dist[v] := infinity ; // Unknown distance function from source to v
previous[v] := undefined ; // Previous node in optimal path from source
end for ;
dist[source] := 0 ; // Distance from source to source
Q := the set of all nodes in Graph ; // All nodes in the graph are unoptimized - thus are in Q
while Q is not empty: // The main loop
u := vertex in Q with smallest distance in dist[] ;
if dist[u] = infinity:
break ; // all remaining vertices are inaccessible from source
end if ;
remove u from Q ;
for each neighbor v of u: // where v has not yet been removed from Q.
alt := dist[u] + dist_between(u, v) ;
if alt < dist[v]: // Relax (u,v,a)
dist[v] := alt ;
previous[v] := u ;
decrease-key v in Q; // Reorder v in the Queue
end if ;
end for ;
end while ;
return dist[] ;
end Dijkstra.
Reference :