Recent from talks
Nothing was collected or created yet.
Dijkstra's algorithm
View on Wikipedia
Dijkstra's algorithm to find the shortest path between a and b. It picks the unvisited vertex with the lowest distance, calculates the distance through it to each unvisited neighbor, and updates the neighbor's distance if smaller. Mark visited (set to red) when done with neighbors. | |
| Class | Search algorithm Greedy algorithm Dynamic programming[1] |
|---|---|
| Data structure | Graph Usually used with priority queue or heap for optimization[2][3] |
| Worst-case performance | [3] |
Dijkstra's algorithm (/ˈdaɪkstrəz/ DYKE-strəz) is an algorithm for finding the shortest paths between nodes in a weighted graph, which may represent, for example, a road network. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years later.[4][5][6]
Dijkstra's algorithm finds the shortest path from a given source node to every other node.[7]: 196–206 It can be used to find the shortest path to a specific destination node, by terminating the algorithm after determining the shortest path to the destination node. For example, if the nodes of the graph represent cities, and the costs of edges represent the distances between pairs of cities connected by a direct road, then Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. A common application of shortest path algorithms is network routing protocols, most notably IS-IS (Intermediate System to Intermediate System) and OSPF (Open Shortest Path First). It is also employed as a subroutine in algorithms such as Johnson's algorithm.
The algorithm uses a min-priority queue data structure for selecting the shortest paths known so far. Before more advanced priority queue structures were discovered, Dijkstra's original algorithm ran in time, where is the number of nodes.[8][9] Fredman & Tarjan 1984 proposed a Fibonacci heap priority queue to optimize the running time complexity to . This is asymptotically the fastest known single-source shortest-path algorithm for arbitrary directed graphs with unbounded non-negative weights. However, specialized cases (such as bounded/integer weights, directed acyclic graphs etc.) can be improved further. If preprocessing is allowed, algorithms such as contraction hierarchies can be up to seven orders of magnitude faster.
Dijkstra's algorithm is commonly used on graphs where the edge weights are positive integers or real numbers. It can be generalized to any graph where the edge weights are partially ordered, provided the subsequent labels (a subsequent label is produced when traversing an edge) are monotonically non-decreasing.[10][11]
In many fields, particularly artificial intelligence, Dijkstra's algorithm or a variant offers a uniform cost search and is formulated as an instance of the more general idea of best-first search.[12]
History
[edit]What is the shortest way to travel from Rotterdam to Groningen, in general: from given city to given city. It is the algorithm for the shortest path, which I designed in about twenty minutes. One morning I was shopping in Amsterdam with my young fiancée, and tired, we sat down on the café terrace to drink a cup of coffee and I was just thinking about whether I could do this, and I then designed the algorithm for the shortest path. As I said, it was a twenty-minute invention. In fact, it was published in '59, three years later. The publication is still readable, it is, in fact, quite nice. One of the reasons that it is so nice was that I designed it without pencil and paper. I learned later that one of the advantages of designing without pencil and paper is that you are almost forced to avoid all avoidable complexities. Eventually, that algorithm became to my great amazement, one of the cornerstones of my fame.
— Edsger Dijkstra, in an interview with Philip L. Frana, Communications of the ACM, 2001[5]
Dijkstra thought about the shortest path problem while working as a programmer at the Mathematical Center in Amsterdam in 1956. He wanted to demonstrate the capabilities of the new ARMAC computer.[13] His objective was to choose a problem and a computer solution that non-computing people could understand. He designed the shortest path algorithm and later implemented it for ARMAC for a slightly simplified transportation map of 64 cities in the Netherlands (he limited it to 64, so that 6 bits would be sufficient to encode the city number).[5] A year later, he came across another problem advanced by hardware engineers working on the institute's next computer: minimize the amount of wire needed to connect the pins on the machine's back panel. As a solution, he re-discovered Prim's minimal spanning tree algorithm (known earlier to Jarník, and also rediscovered by Prim).[14][15] Dijkstra published the algorithm in 1959, two years after Prim and 29 years after Jarník.[16][17]
Algorithm
[edit]
The algorithm requires a starting node, and computes the shortest distance from that starting node to each other node. Dijkstra's algorithm starts with infinite distances and tries to improve them step by step:
- Create a set of all unvisited nodes: the unvisited set.
- Assign to every node a distance from start value: for the starting node, it is zero, and for all other nodes, it is infinity, since initially no path is known to these nodes. During execution, the distance of a node N is the length of the shortest path discovered so far between the starting node and N.[18]
- From the unvisited set, select the current node to be the one with the smallest (finite) distance; initially, this is the starting node (distance zero). If the unvisited set is empty, or contains only nodes with infinite distance (which are unreachable), then the algorithm terminates by skipping to step 6. If the only concern is the path to a target node, the algorithm terminates once the current node is the target node. Otherwise, the algorithm continues.
- For the current node, consider all of its unvisited neighbors and update their distances through the current node; compare the newly calculated distance to the one currently assigned to the neighbor and assign the smaller one to it. For example, if the current node A is marked with a distance of 6, and the edge connecting it with its neighbor B has length 2, then the distance to B through A is 6 + 2 = 8. If B was previously marked with a distance greater than 8, then update it to 8 (the path to B through A is shorter). Otherwise, keep its current distance (the path to B through A is not the shortest).
- After considering all of the current node's unvisited neighbors, the current node is removed from the unvisited set. Thus a visited node is never rechecked, which is correct because the distance recorded on the current node is minimal (as ensured in step 3), and thus final. Repeat from step 3.
- Once the loop exits (steps 3–5), every visited node contains its shortest distance from the starting node.
Description
[edit]The shortest path between two intersections on a city map can be found by this algorithm using pencil and paper. Every intersection is listed on a separate line: one is the starting point and is labeled (given a distance of) 0. Every other intersection is initially labeled with a distance of infinity. This is done to note that no path to these intersections has yet been established. At each iteration one intersection becomes the current intersection. For the first iteration, this is the starting point.
From the current intersection, the distance to every neighbor (directly-connected) intersection is assessed by summing the label (value) of the current intersection and the distance to the neighbor and then relabeling the neighbor with the lesser of that sum and the neighbor's existing label. I.e., the neighbor is relabeled if the path to it through the current intersection is shorter than previously assessed paths. If so, mark the road to the neighbor with an arrow pointing to it, and erase any other arrow that points to it. After the distances to each of the current intersection's neighbors have been assessed, the current intersection is marked as visited. The unvisited intersection with the smallest label becomes the current intersection and the process repeats until all nodes with labels less than the destination's label have been visited.
Once no unvisited nodes remain with a label smaller than the destination's label, the remaining arrows show the shortest path.
Pseudocode
[edit]In the following pseudocode, dist is an array that contains the current distances from the source to other vertices, i.e. dist[u] is the current distance from the source to the vertex u. The prev array contains pointers to previous-hop nodes on the shortest path from source to the given vertex (equivalently, it is the next-hop on the path from the given vertex to the source). The code u ← vertex in Q with min dist[u], searches for the vertex u in the vertex set Q that has the least dist[u] value. Graph.Edges(u, v) returns the length of the edge joining (i.e. the distance between) the two neighbor-nodes u and v. The variable alt on line 14 is the length of the path from the source node to the neighbor node v if it were to go through u. If this path is shorter than the current shortest path recorded for v, then the distance of v is updated to alt.[7]

1 function Dijkstra(Graph, source): 2 3 for each vertex v in Graph.Vertices: 4 dist[v] ← INFINITY 5 prev[v] ← UNDEFINED 6 add v to Q 7 dist[source] ← 0 8 9 while Q is not empty: 10 u ← vertex in Q with minimum dist[u] 11 Q.remove(u) 12 13 for each arc (u, v) in Q: 14 alt ← dist[u] + Graph.Edges(u, v) 15 if alt < dist[v]: 16 dist[v] ← alt 17 prev[v] ← u 18 19 return dist[], prev[]
To find the shortest path between vertices source and target, the search terminates after line 10 if u = target. The shortest path from source to target can be obtained by reverse iteration:
1 S ← empty sequence 2 u ← target 3 if prev[u] is defined or u = source: // Proceed if the vertex is reachable 4 while u is defined: // Construct the shortest path with a stack S 5 S.push(u) // Push the vertex onto the stack 6 u ← prev[u] // Traverse from target to source
Now sequence S is the list of vertices constituting one of the shortest paths from source to target, or the empty sequence if no path exists.
A more general problem is to find all the shortest paths between source and target (there might be several of the same length). Then instead of storing only a single node in each entry of prev[] all nodes satisfying the relaxation condition can be stored. For example, if both r and source connect to target and they lie on different shortest paths through target (because the edge cost is the same in both cases), then both r and source are added to prev[target]. When the algorithm completes, prev[] data structure describes a graph that is a subset of the original graph with some edges removed. Its key property is that if the algorithm was run with some starting node, then every path from that node to any other node in the new graph is the shortest path between those nodes graph, and all paths of that length from the original graph are present in the new graph. Then to actually find all these shortest paths between two given nodes, a path finding algorithm on the new graph, such as depth-first search would work.
Using a priority queue
[edit]A min-priority queue is an abstract data type that provides 3 basic operations: add_with_priority(), decrease_priority() and extract_min(). As mentioned earlier, using such a data structure can lead to faster computing times than using a basic queue. Notably, Fibonacci heap[19] or Brodal queue offer optimal implementations for those 3 operations. As the algorithm is slightly different in appearance, it is mentioned here, in pseudocode as well:
1 function Dijkstra(Graph, source): 2 Q ← Queue storing vertex priority 3 4 dist[source] ← 0 // Initialization 5 Q.add_with_priority(source, 0) // associated priority equals dist[·] 6 7 for each vertex v in Graph.Vertices: 8 if v ≠ source 9 prev[v] ← UNDEFINED // Predecessor of v 10 dist[v] ← INFINITY // Unknown distance from source to v 11 Q.add_with_priority(v, INFINITY) 12 13 14 while Q is not empty: // The main loop 15 u ← Q.extract_min() // Remove and return best vertex 16 for each arc (u, v) : // Go through all v neighbors of u 17 alt ← dist[u] + Graph.Edges(u, v) 18 if alt < dist[v]: 19 prev[v] ← u 20 dist[v] ← alt 21 Q.decrease_priority(v, alt) 22 23 return (dist, prev)
Instead of filling the priority queue with all nodes in the initialization phase, it is possible to initialize it to contain only source; then, inside the if alt < dist[v] block, the decrease_priority() becomes an add_with_priority() operation.[7]: 198
Yet another alternative is to add nodes unconditionally to the priority queue and to instead check after extraction (u ← Q.extract_min()) that it isn't revisiting, or that no shorter connection was found yet in the if alt < dist[v] block. This can be done by additionally extracting the associated priority p from the queue and only processing further if p == dist[u] inside the while Q is not empty loop.[20]
These alternatives can use entirely array-based priority queues without decrease-key functionality, which have been found to achieve even faster computing times in practice. However, the difference in performance was found to be narrower for denser graphs.[21]
Proof
[edit]To prove the correctness of Dijkstra's algorithm, mathematical induction can be used on the number of visited nodes.[22]
Invariant hypothesis: For each visited node v, dist[v] is the shortest distance from source to v, and for each unvisited node u, dist[u] is the shortest distance from source to u when traveling via visited nodes only, or infinity if no such path exists. (Note: we do not assume dist[u] is the actual shortest distance for unvisited nodes, while dist[v] is the actual shortest distance)
Base case
[edit]The base case is when there is just one visited node, source. Its distance is defined to be zero, which is the shortest distance, since negative weights are not allowed. Hence, the hypothesis holds.
Induction
[edit]Assuming that the hypothesis holds for visited nodes, to show it holds for nodes, let u be the next visited node, i.e. the node with minimum dist[u]. The claim is that dist[u] is the shortest distance from source to u.
The proof is by contradiction. If a shorter path were available, then this shorter path either contains another unvisited node or not.
- In the former case, let w be the first unvisited node on this shorter path. By induction, the shortest paths from source to u and w through visited nodes only have costs
dist[u]anddist[w]respectively. This means the cost of going from source to u via w has the cost of at leastdist[w]+ the minimal cost of going from w to u. As the edge costs are positive, the minimal cost of going from w to u is a positive number. However,dist[u]is at mostdist[w]because otherwise w would have been picked by the priority queue instead of u. This is a contradiction, since it has already been established thatdist[w]+ a positive number <dist[u]. - In the latter case, let w be the last but one node on the shortest path. That means
dist[w] + Graph.Edges[w,u] < dist[u]. That is a contradiction because by the time w is visited, it should have setdist[u]to at mostdist[w] + Graph.Edges[w,u].
For all other visited nodes v, the dist[v] is already known to be the shortest distance from source already, because of the inductive hypothesis, and these values are unchanged.
After processing u, it is still true that for each unvisited node w, dist[w] is the shortest distance from source to w using visited nodes only. Any shorter path that did not use u, would already have been found, and if a shorter path used u it would have been updated when processing u.
After all nodes are visited, the shortest path from source to any node v consists only of visited nodes. Therefore, dist[v] is the shortest distance.
Running time
[edit]Bounds of the running time of Dijkstra's algorithm on a graph with edges E and vertices V can be expressed as a function of the number of edges, denoted , and the number of vertices, denoted , using big-O notation. The complexity bound depends mainly on the data structure used to represent the set Q. In the following, upper bounds can be simplified because is for any simple graph, but that simplification disregards the fact that in some problems, other upper bounds on may hold.
For any data structure for the vertex set Q, the running time is:[2]
where and are the complexities of the decrease-key and extract-minimum operations in Q, respectively.
The simplest version of Dijkstra's algorithm stores the vertex set Q as a linked list or array, and edges as an adjacency list or matrix. In this case, extract-minimum is simply a linear search through all vertices in Q, so the running time is .
For sparse graphs, that is, graphs with far fewer than edges, Dijkstra's algorithm can be implemented more efficiently by storing the graph in the form of adjacency lists and using a self-balancing binary search tree, binary heap, pairing heap, Fibonacci heap or a priority heap as a priority queue to implement extracting minimum efficiently. To perform decrease-key steps in a binary heap efficiently, it is necessary to use an auxiliary data structure that maps each vertex to its position in the heap, and to update this structure as the priority queue Q changes. With a self-balancing binary search tree or binary heap, the algorithm requires
time in the worst case; for connected graphs this time bound can be simplified to . The Fibonacci heap improves this to
When using binary heaps, the average case time complexity is lower than the worst-case: assuming edge costs are drawn independently from a common probability distribution, the expected number of decrease-key operations is bounded by , giving a total running time of[7]: 199–200
Practical optimizations and infinite graphs
[edit]In common presentations of Dijkstra's algorithm, initially all nodes are entered into the priority queue. This is, however, not necessary: the algorithm can start with a priority queue that contains only one item, and insert new items as they are discovered (instead of doing a decrease-key, check whether the key is in the queue; if it is, decrease its key, otherwise insert it).[7]: 198 This variant has the same worst-case bounds as the common variant, but maintains a smaller priority queue in practice, speeding up queue operations.[12]
Moreover, not inserting all nodes in a graph makes it possible to extend the algorithm to find the shortest path from a single source to the closest of a set of target nodes on infinite graphs or those too large to represent in memory. The resulting algorithm is called uniform-cost search (UCS) in the artificial intelligence literature[12][23][24] and can be expressed in pseudocode as
procedure uniform_cost_search(start) is
node ← start
frontier ← priority queue containing node only
expanded ← empty set
do
if frontier is empty then
return failure
node ← frontier.pop()
if node is a goal state then
return solution(node)
expanded.add(node)
for each of node's neighbors n do
if n is not in expanded and not in frontier then
frontier.add(n)
else if n is in frontier with higher cost
replace existing node with n
Its complexity can be expressed in an alternative way for very large graphs: when C* is the length of the shortest path from the start node to any node satisfying the "goal" predicate, each edge has cost at least ε, and the number of neighbors per node is bounded by b, then the algorithm's worst-case time and space complexity are both in O(b1+⌊C* ⁄ ε⌋).[23]
Further optimizations for the single-target case include bidirectional variants, goal-directed variants such as the A* algorithm (see § Related problems and algorithms), graph pruning to determine which nodes are likely to form the middle segment of shortest paths (reach-based routing), and hierarchical decompositions of the input graph that reduce s–t routing to connecting s and t to their respective "transit nodes" followed by shortest-path computation between these transit nodes using a "highway".[25] Combinations of such techniques may be needed for optimal practical performance on specific problems.[26]
Bidirectional Dijkstra
[edit]Bidirectional Dijkstra is a variant of Dijkstra’s algorithm designed to efficiently compute the shortest path between a given source vertex s and target vertex t, rather than all vertices. The key idea is to run two simultaneous searches: one forward from s on the original graph and one backward from t on the graph with edges reversed. Each search maintains its own tentative distance estimates, priority queue, and set of “settled” vertices. The two frontiers advance toward each other and meet somewhere along the shortest s–t path.[27]
Two distance arrays are maintained: df[v] (distance from s to v) and db[v] (distance from v to t), initialized to ∞ except df[s] = 0 and db[t] = 0. Two priority queues Qf and Qb hold vertices not yet fully processed, and two sets Sf and Sb store vertices whose shortest-path distance is finalized in each direction. A variable μ stores the length of the best full s–t path found so far, initially ∞.
The algorithm repeatedly extracts the minimum-distance vertex from whichever queue currently has the smaller key, relaxes its outgoing (or incoming) edges, and updates μ whenever it discovers a connection between the two settled sets:
- when relaxing edge (u,x) in the forward search and x ∈ Sb,
and symmetrically for the backward search.
A key feature is the stopping condition: once the sum of the current minimum priorities in both queues is at least μ, no yet-unsettled path can improve upon μ. At this point μ equals the true shortest-path distance δ(s,t), and the search terminates.[27]
This criterion avoids a common mistake of halting as soon as the two frontiers touch, which may overlook a shorter alternative crossing elsewhere.
Because each search only needs to explore roughly half of the search space in typical graphs, the bidirectional method often visits far fewer vertices and relaxes far fewer edges than one-directional Dijkstra on single-pair queries. In road-network–like graphs the savings can be dramatic, sometimes reducing the explored region from an exponential-size ball to two smaller half-balls.
The method is widely used in point-to-point routing for maps and navigation software and serves as a base for many speed-up techniques such as the ALT, contraction hierarchies, and reach-based routing.[28]
If the actual shortest path (not just its distance) is desired, predecessor pointers can be stored in both searches. When μ is updated through some crossing vertex x, the algorithm records this meeting point and reconstructs the final route as the forward path from s to x concatenated with the backward path from x to t.
Theoretical research shows that an optimized bidirectional approach can be instance-optimal, meaning no correct algorithm can asymptotically relax fewer edges on the same graph instance.[29]
Optimality for comparison-sorting by distance
[edit]As well as simply computing distances and paths, Dijkstra's algorithm can be used to sort vertices by their distances from a given starting vertex. In 2023, Haeupler, Rozhoň, Tětek, Hladík, and Tarjan (one of the inventors of the 1984 heap), proved that, for this sorting problem on a positively-weighted directed graph, a version of Dijkstra's algorithm with a special heap data structure has a runtime and number of comparisons that is within a constant factor of optimal among comparison-based algorithms for the same sorting problem on the same graph and starting vertex but with variable edge weights. To achieve this, they use a comparison-based heap whose cost of returning/removing the minimum element from the heap is logarithmic in the number of elements inserted after it rather than in the number of elements in the heap.[30][31]
Specialized variants
[edit]When arc weights are small integers (bounded by a parameter ), specialized queues can be used for increased speed. The first algorithm of this type was Dial's algorithm[32] for graphs with positive integer edge weights, which uses a bucket queue to obtain a running time . The use of a Van Emde Boas tree as the priority queue brings the complexity to .[33] Another interesting variant based on a combination of a new radix heap and the well-known Fibonacci heap runs in time .[33] Finally, the best algorithms in this special case run in [34] time and time.[35]
Related problems and algorithms
[edit]Dijkstra's original algorithm can be extended with modifications. For example, sometimes it is desirable to present solutions which are less than mathematically optimal. To obtain a ranked list of less-than-optimal solutions, the optimal solution is first calculated. A single edge appearing in the optimal solution is removed from the graph, and the optimum solution to this new graph is calculated. Each edge of the original solution is suppressed in turn and a new shortest-path calculated. The secondary solutions are then ranked and presented after the first optimal solution.
Dijkstra's algorithm is usually the working principle behind link-state routing protocols. OSPF and IS-IS are the most common.
Unlike Dijkstra's algorithm, the Bellman–Ford algorithm can be used on graphs with negative edge weights, as long as the graph contains no negative cycle reachable from the source vertex s. The presence of such cycles means that no shortest path can be found, since the label becomes lower each time the cycle is traversed. (This statement assumes that a "path" is allowed to repeat vertices. In graph theory that is normally not allowed. In theoretical computer science it often is allowed.) It is possible to adapt Dijkstra's algorithm to handle negative weights by combining it with the Bellman-Ford algorithm (to remove negative edges and detect negative cycles): Johnson's algorithm.
The A* algorithm is a generalization of Dijkstra's algorithm that reduces the size of the subgraph that must be explored, if additional information is available that provides a lower bound on the distance to the target.
The process that underlies Dijkstra's algorithm is similar to the greedy process used in Prim's algorithm. Prim's purpose is to find a minimum spanning tree that connects all nodes in the graph; Dijkstra is concerned with only two nodes. Prim's does not evaluate the total weight of the path from the starting node, only the individual edges.
Breadth-first search can be viewed as a special-case of Dijkstra's algorithm on unweighted graphs, where the priority queue degenerates into a FIFO queue.
The fast marching method can be viewed as a continuous version of Dijkstra's algorithm which computes the geodesic distance on a triangle mesh.
Dynamic programming perspective
[edit]From a dynamic programming point of view, Dijkstra's algorithm is a successive approximation scheme that solves the dynamic programming functional equation for the shortest path problem by the Reaching method.[36][37][38]
In fact, Dijkstra's explanation of the logic behind the algorithm:[39]
Problem 2. Find the path of minimum total length between two given nodes P and Q. We use the fact that, if R is a node on the minimal path from P to Q, knowledge of the latter implies the knowledge of the minimal path from P to R.
is a paraphrasing of Bellman's principle of optimality in the context of the shortest path problem.
See also
[edit]Notes
[edit]- ^ Controversial, see Moshe Sniedovich (2006). "Dijkstra's algorithm revisited: the dynamic programming connexion". Control and Cybernetics. 35: 599–620. and below part.
- ^ a b Cormen et al. 2001.
- ^ a b Fredman & Tarjan 1987.
- ^ Richards, Hamilton. "Edsger Wybe Dijkstra". A.M. Turing Award. Association for Computing Machinery. Retrieved 16 October 2017.
At the Mathematical Centre a major project was building the ARMAC computer. For its official inauguration in 1956, Dijkstra devised a program to solve a problem interesting to a nontechnical audience: Given a network of roads connecting cities, what is the shortest route between two designated cities?
- ^ a b c Frana, Phil (August 2010). "An Interview with Edsger W. Dijkstra". Communications of the ACM. 53 (8): 41–47. doi:10.1145/1787234.1787249. S2CID 27009702.
- ^ Dijkstra, E. W. (1959). "A note on two problems in connexion with graphs" (PDF). Numerische Mathematik. 1: 269–271. CiteSeerX 10.1.1.165.7577. doi:10.1007/BF01386390. S2CID 123284777.
- ^ a b c d e Mehlhorn, Kurt; Sanders, Peter (2008). "Chapter 10. Shortest Paths" (PDF). Algorithms and Data Structures: The Basic Toolbox. Springer. doi:10.1007/978-3-540-77978-0. ISBN 978-3-540-77977-3.
- ^ Schrijver, Alexander (2012). "On the history of the shortest path problem" (PDF). Optimization Stories. Documenta Mathematica Series. Vol. 6. pp. 155–167. doi:10.4171/dms/6/19. ISBN 978-3-936609-58-5.
- ^ Leyzorek et al. 1957.
- ^ Szcześniak, Ireneusz; Jajszczyk, Andrzej; Woźna-Szcześniak, Bożena (2019). "Generic Dijkstra for optical networks". Journal of Optical Communications and Networking. 11 (11): 568–577. arXiv:1810.04481. doi:10.1364/JOCN.11.000568. S2CID 52958911.
- ^ Szcześniak, Ireneusz; Woźna-Szcześniak, Bożena (2023), "Generic Dijkstra: Correctness and tractability", NOMS 2023-2023 IEEE/IFIP Network Operations and Management Symposium, pp. 1–7, arXiv:2204.13547, doi:10.1109/NOMS56928.2023.10154322, ISBN 978-1-6654-7716-1, S2CID 248427020
- ^ a b c Felner, Ariel (2011). Position Paper: Dijkstra's Algorithm versus Uniform Cost Search or a Case Against Dijkstra's Algorithm. Proc. 4th Int'l Symp. on Combinatorial Search. Archived from the original on 18 February 2020. Retrieved 12 February 2015. In a route-finding problem, Felner finds that the queue can be a factor 500–600 smaller, taking some 40% of the running time.
- ^ "ARMAC". Unsung Heroes in Dutch Computing History. 2007. Archived from the original on 13 November 2013.
- ^ Dijkstra, Edsger W., Reflections on "A note on two problems in connexion with graphs (PDF)
- ^ Tarjan, Robert Endre (1983), Data Structures and Network Algorithms, CBMS_NSF Regional Conference Series in Applied Mathematics, vol. 44, Society for Industrial and Applied Mathematics, p. 75,
The third classical minimum spanning tree algorithm was discovered by Jarník and rediscovered by Prim and Dikstra; it is commonly known as Prim's algorithm.
- ^ Prim, R.C. (1957). "Shortest connection networks and some generalizations" (PDF). Bell System Technical Journal. 36 (6): 1389–1401. Bibcode:1957BSTJ...36.1389P. doi:10.1002/j.1538-7305.1957.tb01515.x. Archived from the original (PDF) on 18 July 2017. Retrieved 18 July 2017.
- ^ V. Jarník: O jistém problému minimálním [About a certain minimal problem], Práce Moravské Přírodovědecké Společnosti, 6, 1930, pp. 57–63. (in Czech)
- ^ Gass, Saul; Fu, Michael (2013). "Dijkstra's Algorithm". In Gass, Saul I; Fu, Michael C (eds.). Encyclopedia of Operations Research and Management Science. Vol. 1. Springer. doi:10.1007/978-1-4419-1153-7. ISBN 978-1-4419-1137-7 – via Springer Link.
- ^ Fredman & Tarjan 1984.
- ^ Observe that p < dist[u] cannot ever hold because of the update dist[v] ← alt when updating the queue. See https://cs.stackexchange.com/questions/118388/dijkstra-without-decrease-key for discussion.
- ^ Chen, M.; Chowdhury, R. A.; Ramachandran, V.; Roche, D. L.; Tong, L. (2007). Priority Queues and Dijkstra's Algorithm – UTCS Technical Report TR-07-54 – 12 October 2007 (PDF). Austin, Texas: The University of Texas at Austin, Department of Computer Sciences.
- ^ Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2022) [1990]. "22". Introduction to Algorithms (4th ed.). MIT Press and McGraw-Hill. pp. 622–623. ISBN 0-262-04630-X.
- ^ a b Russell, Stuart; Norvig, Peter (2009) [1995]. Artificial Intelligence: A Modern Approach (3rd ed.). Prentice Hall. pp. 75, 81. ISBN 978-0-13-604259-4.
- ^ Sometimes also least-cost-first search: Nau, Dana S. (1983). "Expert computer systems" (PDF). Computer. 16 (2). IEEE: 63–85. doi:10.1109/mc.1983.1654302. S2CID 7301753.
- ^ Wagner, Dorothea; Willhalm, Thomas (2007). Speed-up techniques for shortest-path computations. STACS. pp. 23–36.
- ^ Bauer, Reinhard; Delling, Daniel; Sanders, Peter; Schieferdecker, Dennis; Schultes, Dominik; Wagner, Dorothea (2010). "Combining hierarchical and goal-directed speed-up techniques for Dijkstra's algorithm". ACM Journal of Experimental Algorithmics. 15: 2.1. doi:10.1145/1671970.1671976. S2CID 1661292.
- ^ a b Thomas, Mark (30 May 2020). "Bidirectional Dijkstra". UCL Mathematics Blog. Retrieved 3 October 2025.
- ^ Goldberg, Andrew V.; Harrelson, Chris (2005). “Computing the Shortest Path: A* Search Meets Graph Theory.” In: Proceedings of the Sixteenth Annual ACM–SIAM Symposium on Discrete Algorithms (SODA).
- ^ Haeupler, Bernhard; Hladík, Radek; Rozhoň, Václav; Tarjan, Robert E.; Tětek, Jakub (2024). “Bidirectional Dijkstra’s Algorithm is Instance-Optimal.” arXiv:2410.14638.
- ^ Haeupler, Bernhard; Hladík, Richard; Rozhoň, Václav; Tarjan, Robert; Tětek, Jakub (28 October 2024). "Universal Optimality of Dijkstra via Beyond-Worst-Case Heaps". arXiv:2311.11793 [cs.DS].
- ^ Brubaker, Ben (25 October 2024). "Computer Scientists Establish the Best Way to Traverse a Graph". Quanta Magazine. Retrieved 9 December 2024.
- ^ Dial 1969.
- ^ a b Ahuja et al. 1990.
- ^ Thorup 2000.
- ^ Raman 1997.
- ^ Sniedovich, M. (2006). "Dijkstra's algorithm revisited: the dynamic programming connexion" (PDF). Journal of Control and Cybernetics. 35 (3): 599–620. Online version of the paper with interactive computational modules.
- ^ Denardo, E.V. (2003). Dynamic Programming: Models and Applications. Mineola, NY: Dover Publications. ISBN 978-0-486-42810-9.
- ^ Sniedovich, M. (2010). Dynamic Programming: Foundations and Principles. Francis & Taylor. ISBN 978-0-8247-4099-3.
- ^ Dijkstra 1959, p. 270.
References
[edit]- Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2001). "Section 24.3: Dijkstra's algorithm". Introduction to Algorithms (Second ed.). MIT Press and McGraw–Hill. pp. 595–601. ISBN 0-262-03293-7.
- Dial, Robert B. (1969). "Algorithm 360: Shortest-path forest with topological ordering [H]". Communications of the ACM. 12 (11): 632–633. doi:10.1145/363269.363610. S2CID 6754003.
- Fredman, Michael Lawrence; Tarjan, Robert E. (1984). Fibonacci heaps and their uses in improved network optimization algorithms. 25th Annual Symposium on Foundations of Computer Science. IEEE. pp. 338–346. doi:10.1109/SFCS.1984.715934.
- Fredman, Michael Lawrence; Tarjan, Robert E. (1987). "Fibonacci heaps and their uses in improved network optimization algorithms". Journal of the Association for Computing Machinery. 34 (3): 596–615. doi:10.1145/28869.28874. S2CID 7904683.
- Zhan, F. Benjamin; Noon, Charles E. (February 1998). "Shortest Path Algorithms: An Evaluation Using Real Road Networks". Transportation Science. 32 (1): 65–73. doi:10.1287/trsc.32.1.65. S2CID 14986297.
- Leyzorek, M.; Gray, R. S.; Johnson, A. A.; Ladew, W. C.; Meaker, Jr., S. R.; Petry, R. M.; Seitz, R. N. (1957). Investigation of Model Techniques – First Annual Report – 6 June 1956 – 1 July 1957 – A Study of Model Techniques for Communication Systems. Cleveland, Ohio: Case Institute of Technology.
- Knuth, D.E. (1977). "A Generalization of Dijkstra's Algorithm". Information Processing Letters. 6 (1): 1–5. doi:10.1016/0020-0190(77)90002-3.
- Ahuja, Ravindra K.; Mehlhorn, Kurt; Orlin, James B.; Tarjan, Robert E. (April 1990). "Faster Algorithms for the Shortest Path Problem" (PDF). Journal of the ACM. 37 (2): 213–223. doi:10.1145/77600.77615. hdl:1721.1/47994. S2CID 5499589.
- Raman, Rajeev (1997). "Recent results on the single-source shortest paths problem". SIGACT News. 28 (2): 81–87. doi:10.1145/261342.261352. S2CID 18031586.
- Thorup, Mikkel (2000). "On RAM priority Queues". SIAM Journal on Computing. 30 (1): 86–109. doi:10.1137/S0097539795288246. S2CID 5221089.
- Thorup, Mikkel (1999). "Undirected single-source shortest paths with positive integer weights in linear time". Journal of the ACM. 46 (3): 362–394. doi:10.1145/316542.316548. S2CID 207654795.
External links
[edit]- Oral history interview with Edsger W. Dijkstra, Charles Babbage Institute, University of Minnesota, Minneapolis
- Implementation of Dijkstra's algorithm using TDD, Robert Cecil Martin, The Clean Code Blog
Dijkstra's algorithm
View on GrokipediaHistory
Origins and Development
Edsger W. Dijkstra, a pioneering Dutch computer scientist and theoretical physicist by training, joined the Mathematical Centre in Amsterdam in 1952 as a programmer, where he shifted his focus from physics to computing under the influence of Adriaan van Wijngaarden.[6] At the Centre, a key institution for early Dutch computing research, Dijkstra contributed to significant hardware initiatives, including the development of the ARMAC, one of the first stored-program computers in Europe.[7] His work there emphasized practical programming challenges in an era without high-level languages, relying instead on assembly and machine code.[8] In 1956, Dijkstra invented the algorithm while addressing a need for the ARMAC's official inauguration demonstration, aiming to showcase the machine's potential to a non-technical audience through a relatable problem: computing the shortest path in a weighted graph representing a road network between Dutch cities such as Rotterdam and Groningen.[9] This creation was motivated by routing optimization challenges in computer hardware design and communication networks, where efficient pathfinding was essential for interconnecting components or signals.[6] He devised the core method mentally in approximately 20 minutes during a coffee break while shopping in Amsterdam with his fiancée, Maria Debets, without using pencil or paper.[9] The algorithm, initially implemented on the ARMAC using a simplified map of 64 cities encoded in 6 bits, highlighted the practical utility of graph-based computations in hardware contexts.[8] Although formulated and applied in 1956, the algorithm remained unpublished for three years, circulating initially through internal notes at the Mathematical Centre.[10] Dijkstra formalized it in a brief unpublished manuscript in 1959 before its peer-reviewed appearance later that year in Numerische Mathematik as part of the paper "A note on two problems in connexion with graphs," where it was presented alongside a solution to the minimum spanning tree problem.[11] This publication marked the algorithm's entry into the academic literature, establishing Dijkstra's early reputation in combinatorial optimization.[9] The method, now known as Dijkstra's algorithm, reflects his emphasis on elegant, efficient solutions to real-world routing dilemmas in both hardware and network systems.[6]Initial Publication and Impact
Dijkstra's algorithm was formally introduced in the 1959 paper "A note on two problems in connexion with graphs," published in the journal Numerische Mathematik.[2] The three-page article presented the algorithm as a solution to finding shortest paths in weighted graphs with non-negative edge weights, alongside a solution to the minimum spanning tree problem.[2] Following its publication, the algorithm saw rapid adoption within operations research and graph theory communities during the 1960s, where it became a standard tool for solving network optimization problems.[12] This early embrace highlighted its efficiency and versatility, distinguishing it from contemporaneous methods like those proposed by Ford and Fulkerson.[12] The algorithm's influence extended to practical network applications, notably shaping the shortest path first (SPF) routing protocol implemented in the ARPANET in the late 1970s, which computed optimal packet paths across the network.[13] By establishing reliable methods for path computation in dynamic graphs, it solidified shortest path algorithms as a foundational topic in computer science curricula and research.[14] Edsger W. Dijkstra received the 1972 ACM Turing Award for his fundamental contributions to programming and algorithm design, with the shortest path algorithm recognized as a key element of his enduring legacy in the field.[9] Since the 1970s, the algorithm has appeared prominently in seminal textbooks, such as Donald Knuth's The Art of Computer Programming (Volume 3, 1973), ensuring its central role in education and further developments in graph algorithms.[15]Problem Formulation
Shortest Path Problem
The single-source shortest path (SSSP) problem, which Dijkstra's algorithm solves, requires computing the minimum-weight paths from a given source vertex to all other vertices in a graph. Formally, the input is a graph , where is the set of vertices and is the set of edges (which may be directed or undirected), along with a weight function assigning non-negative weights to edges, and a source vertex . The objective is to determine the shortest path distances for every vertex , where denotes the minimum total weight of any path from to , or infinity if no such path exists.[2][16] The length of a path in this context is the sum of the weights of its constituent edges. The algorithm's output is typically an array of these distances , and often includes a predecessor structure—such as an array or tree—that allows reconstruction of the actual shortest paths by tracing back from each target vertex to the source.[16][17] To illustrate, consider a simple undirected graph with vertices , source , and edges with weights: -: 1, -: 4, -: 2, -: 5, -: 1. The shortest path distances from are , (direct edge), (path --), and (path ---). This problem formulation differs from the all-pairs shortest paths problem, which computes distances between every pair of vertices and is addressed by algorithms such as Floyd-Warshall. Unlike variants permitting negative edge weights, which necessitate approaches like Bellman-Ford to handle potential negative cycles, the SSSP assumes non-negative weights to ensure optimality without such complications.[18][16]Graph Assumptions and Inputs
Dijkstra's algorithm requires that all edge weights in the graph are non-negative, denoted as for every edge , to ensure the greedy selection of vertices produces optimal shortest paths.[19] This assumption prevents the possibility of negative cycles, as negative weights would violate the non-negativity condition and could lead to undefined shortest paths; however, the non-negativity alone suffices to guarantee correctness without needing an explicit check for negative cycles.[3] The algorithm applies to finite graphs, which may be directed or undirected; in the undirected case, edges are treated as bidirectional with symmetric weights.[19] For disconnected graphs, the algorithm correctly assigns infinite distances to vertices unreachable from the source, using to represent such cases.[20] The input to Dijkstra's algorithm consists of a graph , a source vertex , and a weight function assigning non-negative weights to edges.[19] The graph is typically represented using an adjacency list, where each vertex points to a list of its neighboring vertices along with the corresponding edge weights, enabling efficient traversal; alternatively, an adjacency matrix can be used, storing weights in a array for denser graphs.[21][22] The primary output is an array for each vertex , where holds the shortest-path distance from to , initialized to for all and updated to finite values for reachable vertices.[19] Optionally, a predecessor array records the parent of in the shortest-path tree, allowing reconstruction of the actual paths from to any reachable ; unreachable vertices retain and have no defined predecessor.[20]Algorithm Overview
Intuitive Explanation
Imagine navigating a city using a map to find the quickest routes from your starting point to various destinations. You begin at a central location and repeatedly choose to explore the nearest unvisited neighborhood that you haven't fully checked yet, updating your estimated travel times to surrounding areas based on the roads you've just traversed. This process mirrors Dijkstra's algorithm, where the "neighborhoods" are graph vertices and the "roads" are weighted edges representing distances or costs. By always prioritizing the closest option, the algorithm systematically uncovers the shortest paths without backtracking unnecessarily.[23] At its core, the algorithm operates greedily: it maintains tentative distance estimates from the source vertex to all others, initially setting the source's distance to zero and others to infinity. It then selects the unprocessed vertex with the smallest known distance, "settles" it as final, and relaxes its outgoing edges to potentially shorten the estimates for neighboring vertices. This selection and update cycle continues until all vertices are settled, building a tree of shortest paths. A priority queue can efficiently manage the selection of the next vertex, though the intuition holds regardless of implementation details.[5][24] The algorithm's reliability stems from the assumption of non-negative edge weights, which ensures that once a vertex's distance is settled, no shorter path can emerge later through unprocessed vertices—preventing the need to revisit and revise earlier choices. Intuitively, with positive or zero costs, the "wavefront" of explored paths expands outward without contractions, guaranteeing that greedy selections capture optimal routes. If negative weights were present, this expansion could loop indefinitely or require more complex handling, but non-negative weights keep the process straightforward and correct.[25][5] Consider a simple weighted graph with vertices S (source), A, B, and T (target), and edges: S-A (weight 4), S-B (weight 2), A-T (weight 1), B-T (weight 5). Start with distances: S=0, A=∞, B=∞, T=∞.- Select S (distance 0); relax edges to update A=4 and B=2.
- Next, select B (smallest distance 2); relax to T, updating T=7 (2+5).
- Then, select A (distance 4); relax to T, improving T=5 (4+1).
- Finally, select T (distance 5), completing the paths.
Key Data Structures
Dijkstra's algorithm employs a set of core data structures to track and update shortest path estimates across the graph's vertices. These structures enable the systematic selection of vertices for permanent distance assignment and the propagation of distance improvements to adjacent nodes.[11] The distance array, typically denoted as for each vertex , holds the current estimate of the shortest path distance from the source vertex to . Upon initialization, and for all , reflecting that no paths have been discovered yet except to the source itself. As the algorithm progresses, is updated only if a shorter path is found through relaxation, ensuring it always represents the best-known distance.[26][27] Complementing the distance array is the predecessor array , which records the immediate predecessor of each vertex along the shortest path from . Initialized to nil for all vertices, is updated during relaxation whenever decreases, effectively building a shortest path tree that allows path reconstruction by backtracking from any target vertex to the source.[26][27] To distinguish vertices whose distances are finalized from those still under consideration, the algorithm uses a set of settled vertices, starting empty and growing as vertices are selected and their distances confirmed as shortest. The unsettled vertices, implicitly where is the vertex set, represent nodes with tentative distances subject to potential improvement. This partitioning ensures that once a vertex enters , no further updates occur to its distance.[26][27] For efficient selection of the unsettled vertex with the minimum , a priority queue stores all unsettled vertices, prioritized by their current distance estimates. supports insertion of vertices initially and extract-min operations to retrieve and settle the next candidate, facilitating the core loop of distance minimization and relaxation.[26][27]Detailed Description
Initialization Phase
The initialization phase of Dijkstra's algorithm establishes the starting conditions for computing shortest paths from a designated source vertex in a weighted graph with nonnegative edge weights. This phase sets up the distance estimates and predecessor information for all vertices, prepares a collection of unsettled vertices, and populates a priority queue to facilitate the selection of the next vertex to process. These steps ensure that the algorithm begins with a well-defined state where only the source has a finite distance, and all other vertices are marked as unreachable initially.[24][28] First, the algorithm initializes a distance array and a predecessor array for each vertex . The distance to the source is set to zero, i.e., , and its predecessor is set to null, , reflecting that no path precedes the source itself. For all other vertices , the distances are set to infinity, , and their predecessors to null, , indicating that no shortest paths have been discovered yet. This setup assumes that infinity represents an unbounded value larger than any possible path length in the graph, ensuring that initial estimates do not bias the search toward incorrect paths.[24][28] Next, the algorithm defines an unsettled set , which initially contains all vertices in , i.e., . This set tracks vertices whose shortest-path distances are not yet finalized, allowing the main loop to iteratively select and settle vertices until is empty. The unsettled set plays a crucial role in maintaining the invariant that unsettled vertices may still have their distances updated based on newly discovered paths.[28] All vertices are then inserted into a priority queue , with each vertex keyed by its current distance estimate . For the source, the key is 0, while all others have key . The priority queue enables efficient extraction of the unsettled vertex with the minimum distance estimate in subsequent phases, guiding the algorithm to explore paths in order of increasing cost.[24][28] Optionally, if the graph is represented using an adjacency list, this phase may include verifying or preparing the list structure, where each vertex points to its neighboring vertices and the corresponding edge weights, to support efficient neighbor traversal during relaxation. This representation is standard for sparse graphs and ensures that edge access is per vertex .[28]Relaxation and Selection Phase
The relaxation and selection phase forms the core iterative process of Dijkstra's algorithm, repeatedly choosing a vertex to settle and updating tentative distances to its neighbors until all reachable vertices are processed. This phase builds upon the initialization, where the source vertex has distance , all other vertices have , and the set of unsettled vertices initially includes all vertices in the graph.[29] While is not empty, the algorithm selects the vertex with the minimum tentative distance , finalizes as the shortest path distance from to , and removes from . This selection ensures that is the next vertex whose shortest path is guaranteed to be correctly computed, given non-negative edge weights.[29] For each neighbor of (i.e., each outgoing edge with weight ), the algorithm applies relaxation: if , it updates to , sets the predecessor to track the path, and decreases the key of in to reflect the improved distance estimate. This step potentially propagates shorter paths through the graph by considering paths that end at the newly settled .[29] The phase terminates when becomes empty, indicating that all vertices have been settled and their distances finalized. Any vertex with at termination is unreachable from , as no path exists to it under the graph's non-negative weights.[29]Pseudocode Implementations
Basic Array-Based Version
The basic array-based version of Dijkstra's algorithm performs the extract-min operation by linearly scanning all unsettled vertices to identify the one with the smallest tentative distance from the source, repeating this process |V| times. This straightforward implementation, which avoids advanced data structures, achieves correctness under the same assumptions as the original algorithm: non-negative edge weights and a connected, directed or undirected graph represented typically via an adjacency list.[24] The algorithm begins by initializing two arrays: the distance array , where for the source vertex and for all other vertices , and the predecessor array , set to NIL for all . A boolean array is also initialized to false for all vertices, tracking which vertices have been permanently finalized. In each of the |V| main iterations, the algorithm scans the unsettled vertices to find the one with the minimum (taking O(|V|) time per scan), marks as settled, and then relaxes all edges outgoing from by updating and for each neighbor if a shorter path is found.[30] Here is the pseudocode for this version:DIJKSTRA(G, w, s)
for each vertex v ∈ G.V
d[v] = ∞
π[v] = NIL
settled[v] = false
d[s] = 0
for i = 1 to |G.V|
// Extract-min: linear scan over unsettled vertices, O(|V|) time
u = NIL
min_dist = ∞
for each vertex v ∈ G.V
if not settled[v] and d[v] < min_dist
min_dist = d[v]
u = v
if u == NIL
break // All remaining vertices are unreachable
settled[u] = true
for each neighbor v of u (i.e., (u,v) ∈ G.E)
if d[v] > d[u] + w(u, v)
d[v] = d[u] + w(u, v)
π[v] = u
DIJKSTRA(G, w, s)
for each vertex v ∈ G.V
d[v] = ∞
π[v] = NIL
settled[v] = false
d[s] = 0
for i = 1 to |G.V|
// Extract-min: linear scan over unsettled vertices, O(|V|) time
u = NIL
min_dist = ∞
for each vertex v ∈ G.V
if not settled[v] and d[v] < min_dist
min_dist = d[v]
u = v
if u == NIL
break // All remaining vertices are unreachable
settled[u] = true
for each neighbor v of u (i.e., (u,v) ∈ G.E)
if d[v] > d[u] + w(u, v)
d[v] = d[u] + w(u, v)
π[v] = u
Priority Queue Version
The priority queue version of Dijkstra's algorithm enhances efficiency by replacing the linear-time minimum selection of the array-based implementation with a data structure that supports faster extraction of the minimum and key updates. This approach uses a generic priority queue, typically implemented as a binary heap, to maintain vertices ordered by their current shortest-path distance estimates from the source. The queue supports two key operations: EXTRACT-MIN to retrieve and remove the vertex with the smallest key, and DECREASE-KEY to reduce the key (distance) of a vertex already in the queue when a shorter path is discovered.[31] The algorithm initializes the priority queue Q with all vertices, each keyed by their initial distance estimate d, which is infinity for all vertices except the source s where d = 0. During execution, when relaxing edges from a selected vertex u, if a neighbor v's distance can be improved, the algorithm updates d and calls DECREASE-KEY(Q, v, d) to reflect the new lower key in the queue, ensuring the heap's internal structure adjusts the vertex's position accordingly without duplicating entries. This handling avoids the inefficiency of re-inserting vertices, maintaining a single entry per vertex while keeping the queue's size at most |V|.[31][27] The pseudocode assumes a graph G = (V, E) with non-negative edge weights w(u, v) ≥ 0, directed or undirected, and a priority queue supporting EXTRACT-MIN in O(log |V|) time and DECREASE-KEY in O(log |V|) time, as provided by a binary heap. It also relies on an adjacency list representation for accessing neighbors and arrays d[] and π[] to track distances and predecessors, respectively. Unlike the basic array-based version, which scans all unprocessed vertices for the minimum each time, this version achieves logarithmic-time selections, making it suitable for sparse graphs.[31][27]DIJKSTRA(G, w, s)
1 INITIALIZE-SINGLE-SOURCE(G, s)
2 S ← ∅
3 Q ← V[G] // priority queue with all vertices, keyed by d[v]
4 while Q ≠ ∅
5 do u ← EXTRACT-MIN(Q)
6 S ← S ∪ {u}
7 for each vertex v ∈ Adj[u]
8 do RELAX(u, v, w)
// where RELAX(u, v, w) is:
if d[v] > d[u] + w(u, v)
then d[v] ← d[u] + w(u, v)
π[v] ← u
DECREASE-KEY(Q, v, d[v])
DIJKSTRA(G, w, s)
1 INITIALIZE-SINGLE-SOURCE(G, s)
2 S ← ∅
3 Q ← V[G] // priority queue with all vertices, keyed by d[v]
4 while Q ≠ ∅
5 do u ← EXTRACT-MIN(Q)
6 S ← S ∪ {u}
7 for each vertex v ∈ Adj[u]
8 do RELAX(u, v, w)
// where RELAX(u, v, w) is:
if d[v] > d[u] + w(u, v)
then d[v] ← d[u] + w(u, v)
π[v] ← u
DECREASE-KEY(Q, v, d[v])
Proof of Correctness
Base Case Analysis
The base case for the proof of correctness of Dijkstra's algorithm is established immediately following the initialization phase. In this phase, the distance estimate from the source vertex to itself is set to , which equals the true shortest-path distance , as the path length to itself is zero by definition. For every other vertex , the distance estimate is initialized to , ensuring that holds, since is either a non-negative finite value or infinite in the case of unreachable vertices.[32][33] At this point, the set of settled vertices is empty, so the loop invariant—that for all —holds vacuously true, with no vertices yet permanently labeled. The first iteration of the main loop then extracts the vertex from the priority queue, as it possesses the minimum distance estimate of 0 among all vertices. Upon adding to , the set becomes , and the invariant is satisfied since . No edge relaxations have been performed prior to this extraction, rendering the distances trivially correct for the settled set without any prior adjustments.[32][33] This base case relies on the algorithm's assumption of non-negative edge weights, which ensures no shorter paths can exist that would contradict the initial estimates, although the trivial nature of the starting point introduces no contradictions even without relaxations.[32]Inductive Invariant
The inductive invariant for Dijkstra's algorithm ensures that the distance estimates remain correct throughout execution, providing a foundation for proving the algorithm's overall correctness. Specifically, after each vertex is settled (i.e., extracted from the priority queue and added to the set of settled vertices), the invariant states that for all , where is the current distance estimate from the source to , and is the true shortest-path distance from to ; additionally, for all .[33] This invariant holds under the assumption of non-negative edge weights, as negative weights could invalidate the distance estimates during relaxation.[34] The proof of this invariant proceeds by mathematical induction on the size of the settled set . The base case, where and , is established prior to the main loop: , and for all , satisfying the invariant trivially.[35] For the inductive hypothesis, assume the invariant holds after vertices have been settled, for some . Now consider the -th iteration, where the vertex with the smallest is extracted and settled, making . To verify the invariant for the new , first show that . Suppose, for contradiction, that . Consider a shortest path from to . Let be the last vertex on that belongs to (such a vertex exists since ), and let be the successor of on , so and the edge leaves . By the inductive hypothesis, . When was settled, the edge to was relaxed, so . Now, . Since edge weights are non-negative, , so . Therefore, . But , and was selected as the unsettled vertex with minimum , so , a contradiction. Thus, , and the invariant holds for all after settling .[36][33] Next, after relaxing all edges outgoing from , the estimates for unsettled vertices must satisfy . Before relaxation, the invariant ensures for . Relaxation from can only decrease if a shorter path via is found, setting it to , since by the triangle inequality for shortest paths and non-negative weights. Thus, the updated remains . Moreover, no overlooked shorter path from to can exist via unsettled nodes, as that would imply an even shorter path to or contradict the finality of settled distances. Thus, the inductive step holds, preserving the invariant for .[34][35] By induction, the invariant holds after every iteration. When (the full vertex set), all vertices are settled, so for every , confirming that the algorithm computes the correct shortest-path distances from .[36]Complexity Analysis
Time and Space Complexity
Dijkstra's algorithm, in its basic implementation using an array to track the minimum distance vertex, exhibits a time complexity of , where denotes the number of vertices. This arises from performing extract-minimum operations, each requiring time to scan the array, alongside relaxation operations that each take time, where is the number of edges.[27] An enhanced implementation employs a binary heap as a priority queue, reducing the time complexity to . Here, each of the extract-min operations costs , and up to decrease-key operations (for relaxations) each incur time, yielding the overall bound.[27][37] Regarding space complexity, the algorithm requires space for the distance array , predecessor array , and priority queue , in addition to for storing the graph representation.[38][39] The time complexity varies with graph density: for sparse graphs where , the priority queue version approaches ; in dense graphs, can reach , making the bound .[37]Optimizations for Large Graphs
One key optimization for Dijkstra's algorithm on large graphs involves replacing the standard binary heap with a Fibonacci heap as the priority queue data structure. This change supports amortized constant-time decrease-key operations, leading to an overall time complexity of , which is asymptotically superior to the bound of binary heaps for dense graphs.[40] For graphs with small non-negative integer edge weights, Dial's algorithm provides another efficient variant by using a bucket queue (an array of lists indexed by distance values) instead of a general priority queue. This approach achieves a time complexity of , where is the maximum edge weight, making it particularly effective when is small compared to , as it avoids logarithmic factors altogether.[41] In single-target shortest path problems, early termination can significantly reduce computation by halting the algorithm once the target vertex is extracted from the priority queue, as all remaining vertices will have distances at least as large. This optimization is inherent to the greedy selection process and preserves correctness, often yielding substantial speedups on large graphs where the target is reached before processing all vertices.[42] For very large or theoretically infinite graphs, such as those arising in continuous spaces or expansive networks, pure Dijkstra implementations may fail to terminate or become impractical due to unbounded exploration. Label-correcting algorithms, which relax the strict label-setting invariant of Dijkstra and allow multiple updates per vertex, offer a more flexible approach; when combined with node potentials to shift edge weights to non-negative values, they enable efficient computation even in the presence of negative weights or expansive structures.[43] Approximations and heuristics, such as bucketing vertices by distance intervals in Δ-stepping variants, further bound exploration by processing groups of nodes simultaneously, achieving practical performance on massive graphs with time complexities approaching linear in practice for suitable parameter choices.[44]Variants and Extensions
Bidirectional Search
Bidirectional search extends Dijkstra's algorithm to compute the shortest path from a source vertex to a target vertex by performing simultaneous searches from both endpoints, aiming to meet in the middle for improved efficiency. This variant initiates two instances of Dijkstra's algorithm: one forward from and one backward from on the reversed graph, where edge directions are inverted to simulate searching toward . The searches proceed until their explored sets intersect, at which point the shortest path is reconstructed by combining the forward and backward paths meeting at the intersection node. This approach, first formalized as a bidirectional extension of shortest path algorithms, reduces the effective search space compared to unidirectional Dijkstra, particularly in graphs where the shortest path is roughly balanced between and .[45] The mechanics involve maintaining two priority queues—one for each direction—and alternating extractions of the minimum-distance vertex from them to ensure balanced progress. For each extracted vertex, the algorithm relaxes outgoing edges (forward) or incoming edges (backward, via the reversed graph) and updates distances if a shorter path is found. Intersection is checked after each expansion by verifying if the newly settled vertex belongs to the opposite search's settled set, using efficient data structures like hash sets for O(1) lookups. Upon detecting an intersection at vertex , the total path length is the sum of the distances from to and from to , and the path is traced via predecessor pointers from both directions. This process preserves Dijkstra's correctness guarantees, as both sub-searches maintain non-negative distances and settle vertices in increasing order.[45][46] In terms of complexity, bidirectional Dijkstra achieves instance-optimality, with time complexity proportional to the number of edges accessed during the searches plus a logarithmic factor for priority queue operations, often significantly less than full unidirectional Dijkstra. Using a binary heap, the overall time is O((|E_f| + |V_f| \log |V|) + (|E_b| + |V_b| \log |V|)), where subscripts denote forward and backward expansions; in practice, this is roughly half the work of standard Dijkstra for balanced expansions, as each search explores approximately the square root of the unidirectional search space in uniform-cost settings. For unweighted graphs, it is O(\Delta \cdot \min(|E_s|, |E_t|)), where \Delta is the maximum degree, outperforming unidirectional search by a factor up to O(\sqrt{|V|}) in tree-like structures. Empirical studies on random graphs confirm 2-4 times fewer node expansions than unidirectional methods.[46][45] This variant is limited to undirected graphs or directed graphs with symmetric weights, as the backward search requires a valid reversed graph with equivalent costs; asymmetric weights can lead to incorrect paths. It also assumes non-negative edge weights, inheriting Dijkstra's constraints, and may not yield speedup if the meeting point is skewed toward one endpoint, such as in graphs with bottlenecks near or . For example, in a uniform grid graph representing a 2D map (e.g., a 100x100 lattice with unit edge weights), bidirectional search from opposite corners expands roughly \sqrt{2} \times 10^4 nodes total versus 2 \times 10^4 for unidirectional, meeting near the center after exploring diamond-shaped frontiers that intersect midway.[46][45]Parallel Implementations
Parallel implementations of Dijkstra's algorithm adapt the core relaxation phase to leverage multi-core processors, distributed systems, and GPUs, enabling efficient shortest-path computation on large-scale graphs. In shared-memory environments, multi-threading focuses on parallelizing edge relaxations after selecting the minimum-distance vertex, with threads updating distances concurrently while using locks or critical sections to synchronize access to shared distance arrays. For instance, OpenMP implementations partition vertices among threads, applying barriers after each relaxation round to ensure consistency, which yields performance gains on graphs with 1024 or more vertices but suffers from cache coherence overheads.[47] In distributed settings using message-passing interfaces like MPI, the algorithm propagates distance updates asynchronously across processors, each owning a subset of vertices and edges. Processors relax local edges and exchange boundary updates via messages, with global synchronization steps to determine the next minimum-distance vertex, often employing lookahead techniques to process vertices slightly beyond the current frontier for better load balance. The Parallel Boost Graph Library (PBGL) implements this via a distributed priority queue, achieving near-linear strong scaling on random graphs and sub-linear on road networks when tuned with appropriate lookahead factors, such as λ=400 for USA road datasets on clusters with up to 128 nodes.[48] GPU implementations exploit massive parallelism through work-efficient scheduling of relaxations, often using variants like delta-stepping to bucket vertices by distance approximations, enabling parallel prefix sums or scans to process large fronts simultaneously. A notable approach is the Asynchronous Dynamic Delta-Stepping (ADDS) algorithm, which dynamically adjusts bucket counts (up to 32) and uses custom allocators for memory efficiency, outperforming prior GPU methods by 2.9× on average across diverse graphs on NVIDIA RTX 2080 Ti hardware. These adaptations achieve near-linear speedups on well-balanced workloads, such as synthetic random graphs, but face challenges in load balancing for irregular graphs like road networks, where uneven vertex degrees lead to thread or processor idleness and increased synchronization costs.[49]Applications and Related Concepts
Real-World Uses
Dijkstra's algorithm serves as the foundational shortest-path computation mechanism in several link-state routing protocols used for IP packet forwarding in computer networks. In the Open Shortest Path First (OSPF) protocol, routers exchange link-state advertisements to build a complete topology map, upon which Dijkstra's algorithm is applied to calculate the shortest paths from a given source to all destinations, enabling efficient packet routing across autonomous systems.[50] Similarly, the Intermediate System to Intermediate System (IS-IS) protocol integrates Dijkstra's shortest path first (SPF) algorithm to compute forwarding tables based on collected link-state information, supporting both IPv4 and IPv6 environments in large-scale ISP backbones.[51] In transportation systems, Dijkstra's algorithm underpins route optimization in GPS navigation applications by modeling road networks as weighted graphs, where edge weights represent distances, travel times, or traffic conditions. For instance, systems like Google Maps employ variants of Dijkstra's algorithm to determine the shortest routes between origins and destinations, dynamically adjusting weights to account for real-time traffic data and thereby minimizing expected travel time.[52] This approach ensures scalable computation for urban navigation scenarios, handling millions of nodes corresponding to intersections and road segments.[53] Robotics leverages Dijkstra's algorithm for path planning in environments represented as grids or graphs, where nodes denote positions and edges carry costs based on terrain difficulty or obstacle proximity. In mobile robots navigating indoor or outdoor spaces, the algorithm identifies obstacle-avoiding paths by prioritizing low-cost traversals, as demonstrated in applications for substation inspection robots that refine search areas to enhance efficiency in cluttered settings.[54] Such implementations are particularly effective in static or semi-static grids, providing collision-free trajectories that balance computational speed with optimality.[55] In bioinformatics, Dijkstra's algorithm facilitates analysis of protein-protein interaction (PPI) networks by treating proteins as nodes and interactions as weighted edges, often with weights reflecting binding affinities or functional similarities. Researchers apply it to identify shortest paths between disease-associated proteins and potential drug targets, such as in retinoblastoma studies where it traces connectivity in PPI graphs to uncover intermediate genes.[56] This graph-theoretic approach aids in elucidating genetic architectures underlying complex traits, like schizophrenia, by quantifying network distances and highlighting key pathways.[57]Connections to Other Algorithms
Dijkstra's algorithm can be interpreted as a specialized form of dynamic programming tailored to graphs with non-negative edge weights, where it computes shortest paths by relaxing edges in a specific order that respects the principle of optimality. This approach processes vertices in non-decreasing order of their tentative distances from the source, effectively solving the problem on an implicit directed acyclic graph (DAG) induced by these increasing distances.[12] The core of this connection lies in the Bellman equation, which defines the shortest-path distance from the source to a vertex as: where is the set of edges and is the weight of edge . This recursive relation, rooted in Bellman's work on routing problems, ensures that optimal subpaths contribute to the overall shortest path, allowing Dijkstra's greedy selections to align with dynamic programming's successive approximation method.[18][12] A primary alternative to Dijkstra's algorithm is the Bellman-Ford algorithm, which extends the dynamic programming framework to handle graphs containing negative edge weights, provided no negative-weight cycles exist. Unlike Dijkstra's greedy prioritization, Bellman-Ford iteratively relaxes all edges times, achieving a time complexity of , which is less efficient for dense graphs with non-negative weights but necessary when negatives are present.[18] Another related method is the A* algorithm, which builds directly on Dijkstra's framework by incorporating an admissible heuristic to estimate the cost to the goal, prioritizing nodes via , where is the path cost from the source. This heuristic guidance reduces explored nodes in goal-oriented searches, and A* degenerates to Dijkstra when for all .[58] For all-pairs shortest paths, Johnson's algorithm leverages Dijkstra's efficiency by first applying Bellman-Ford to compute potentials for each vertex , reweighting edges as to ensure non-negativity without altering relative path lengths. Dijkstra is then executed from each source in the reweighted graph, yielding an overall time complexity of with Fibonacci heaps, making it suitable for sparse graphs with possible negative weights.[59] The choice among these algorithms depends on graph properties and problem requirements, as summarized below:| Algorithm | Handles Negative Weights | Time Complexity | Primary Use Case |
|---|---|---|---|
| Dijkstra | No | $O(( | V |
| Bellman-Ford | Yes (no negative cycles) | $O( | V |
| A* | No (admissible heuristic required) | Varies with heuristic quality | Informed single-target pathfinding in large spaces |
| Johnson's | Yes (no negative cycles) | $O( | V |

