Dijkstra's algorithm is a classic algorithm in computer science and operations research for finding the shortest paths between nodes in a graph, which may represent, for example, road networks. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years later.
The algorithm exists in many variants; the original version found the shortest path between two nodes, but a more common variant fixes a single node as the "source" node and finds shortest paths from the source to all other nodes in the graph, producing a shortest-path tree.
Here's a high-level description of how the algorithm works:
-
Initialization: Start with a set of nodes, where the source node's distance to itself is zero and all other nodes have an infinite initial distance. The source node is marked as the current node.
-
Set of Visited Nodes: Begin with an empty set of visited nodes. Only the nodes that have been visited and had their distances finalized will be added to this set.
-
Distance Updates: For the current node, consider all of its unvisited neighbors. Calculate the distance from the source node to each neighbor by summing the distance from the source node to the current node and the distance from the current node to the neighbor. If this distance is less than the previously recorded distance for a neighbor, update the neighbor's distance.
-
Finalize the Current Node: Once all neighbors of the current node have been considered, mark the current node as visited and add it to the set of visited nodes. The shortest path to this node is now determined.
-
Select the Next Node: Choose the unvisited node with the smallest recorded distance from the source node as the next "current node."
-
Repeat: Repeat the process of distance updates, node finalization, and next node selection until all nodes have been visited.
-
Termination: The algorithm terminates when all nodes have been visited. At this point, the shortest path to each node has been determined. If you're only interested in the shortest path to a specific node, you can terminate the algorithm early as soon as that node has been visited.
The algorithm assumes that all weights are non-negative, as the presence of negative weight edges would require a different algorithm, such as the Bellman-Ford algorithm, to ensure correct results for shortest paths.
Dijkstra's algorithm can be implemented efficiently using a priority queue, often a min-heap, to select the next node with the smallest distance efficiently. This data structure allows the algorithm to skip over nodes that have already been visited and to quickly find the next node to process. The running time of the algorithm depends on the implementation of the priority queue. Using a simple array or list can result in O(V^2) complexity (where V is the number of vertices), while a binary heap can bring it down to O((V+E) log V), and more sophisticated data structures like Fibonacci heaps can reduce it further to O(E + V log V).