Dijkstra’s algorithm computes the shortest path from a single starting node to every other reachable vertex in a weighted graph where edge costs aren’t negative [1, 2]. Conceived by Dutch computer scientist Edsger W. Dijkstra in 1956, the method assigns zero cost to the start node, sets all other nodes to infinity, and lowers those estimates step by step through a min-priority queue [1, 4]. Pronounced DYKE-strəz from the West Frisian surname, it’s a greedy approach that locks in one vertex at a time [1, 3]. Routing protocols such as Open Shortest Path First (OSPF) and Intermediate System to Intermediate System (IS-IS) still use it to route data [1].
How Dijkstra’s Algorithm Works Step by Step
Graphs model problems by turning locations or intersections into vertices and connecting them with weighted edges that represent distance, travel time, or financial cost. Before any search begins, the algorithm initializes a distance array dist[] with zero at the source node and infinity at every other vertex, while clearing each node’s predecessor pointer. It places the source inside an unvisited priority queue ordered by current distance [1, 2].
At each iteration, the procedure pulls the vertex u with the smallest finite distance from the queue and marks it as visited. It then checks every outgoing edge from u to a neighbor v in a step called relaxation, adding the edge weight to u‘s known distance [1, 4]. In a worked example from Technische Universität München, if reaching a left node costs 20 units and a shortcut edge to a right node costs 1 unit, the relaxed cost becomes 21 units. Whenever that new sum beats the neighbor’s stored distance, the algorithm updates the distance and records u as the new predecessor [1, 2].
Once a node leaves the unvisited queue, it’s never checked again because no shorter route through later vertices can exist without negative edges [1, 4]. The loop stops when the queue empties, or as soon as a specific target vertex gets pulled if only one destination matters. Following predecessor pointers backward from the destination to the source reconstructs the shortest route, while unreachable vertices keep an infinite distance [1, 2]. Storing every tied predecessor during relaxation even lets the routine return all equal-length shortest paths between two nodes [1].

Origins in Amsterdam
Edsger W. Dijkstra (1930–2002) invented the method in 1956 while working as a programmer at the Mathematical Center in Amsterdam [1, 3]. He needed a problem that non-computing visitors could grasp to showcase the capabilities of the new ARMAC computer, and he settled on finding the shortest route between two Dutch cities, Rotterdam and Groningen [1].
Dijkstra recalled designing the procedure in about 20 minutes while sitting on an Amsterdam café terrace with his fiancée during a shopping trip. Because he worked “without pencil and paper,” he later said the mental constraint pushed him to “avoid all avoidable complexities” in the logic. He soon implemented the “twenty-minute invention” on ARMAC using a simplified transportation map of 64 Dutch cities, a limit chosen so 6 bits could encode each city number. A year later, hardware engineers asked him how to minimize wire on the back panel of the institute’s next machine, which led him to independently rediscover Prim’s minimal spanning tree method, originally known to Jarník [1].
Although Dijkstra conceived his shortest-path design in 1956, it reached print three years later in 1959 as a three-page note in the journal Numerische Mathematik [1, 5]. He later remarked that the algorithm became “one of the cornerstones of my fame,” even though he hadn’t expected such wide adoption when he sketched it over coffee [1].
Why Is Dijkstra’s Algorithm Greedy?
Dijkstra’s algorithm is greedy because it always selects the unvisited vertex with the lowest known cost at the current step rather than searching every possible combination of edges ahead of time [1, 4]. Unlike blind greedy heuristics that can get trapped in dead ends, this choice stays exact because edge costs never drop below zero [1, 2].
Proofs of correctness rely on a property known as optimal substructure: every subpath inside a true shortest path must itself be a shortest path. As Melanie Herzog, Wolfgang F. Riedl, and Lisa Velden explain in Technische Universität München’s discrete mathematics materials, if a cheaper route existed between intermediate nodes b and c inside a path a-b-c-d, swapping in that shortcut would produce a shorter path from a to d, contradicting the assumption [2]. Matthew Towers traces the formal proof to CLRS Theorem 24.6, showing that once a vertex u enters the processed set S, its stored value equals the true shortest distance from the start. Because any remaining unvisited node must lie at least as far from the start as every processed node, no future relaxation can undercut an already settled vertex [4].

Empirical tests bear out that guarantee when compared with faster or heuristic alternatives. In a 2021 study published in the International Journal of Advances in Data and Information Systems, M. R. Wayahdi, S. H. N. Ginting, and D. Syahputra compared Greedy, A-Star, and Dijkstra algorithms on path-finding graphs. They found that Greedy finishes fast but often misses the optimal route, A-Star improves on Greedy when graphs carry complex data, and Dijkstra consistently yields optimal results [6].
Why Do Negative Weights Fail?
Negative edge weights break the algorithm’s greedy guarantee because they let a later path reduce a node’s total distance after that node has already been marked final. Once a vertex leaves the unvisited set, its edges won’t be revisited to propagate a surprise discount [1, 2].
Technische Universität München illustrates this failure with a small graph where the algorithm settles on a route to node f with cost 4, even though another path reaches f at cost 3 through a negative edge. Trying to patch the problem by adding a constant to every edge weight doesn’t work either. When Herzog and colleagues took a graph whose cheapest edge had cost -2 and added 2 or 3 to every edge, the original shortest path a-b-c-d-e-g (cost -5) lost out to the two-edge path a-f-g (cost 6), because adding a fixed penalty to each edge penalizes paths with more hops [2].
When negative weights can’t be avoided, developers switch to the Bellman-Ford algorithm, which revisits and updates previously processed vertices [2]. For all-pairs shortest paths in sparse graphs with negative edges, Johnson’s algorithm uses Dijkstra as an internal subroutine after reweighting edges safely. Generalized versions can also handle partially ordered labels as long as traversing an edge never shrinks a label [1].
Priority Queue Runtime
How fast the algorithm runs depends on the number of vertices (V or n), the number of edges (E or m), and the data structure backing the priority queue [1, 2, 4]. Every reachable vertex must be pulled from the queue once, and every outgoing edge must be checked once during relaxation [1, 2].
In Dijkstra’s 1959 formulation using a plain array or list for the queue, scanning for the minimum element n times takes up to n² steps, yielding a time complexity of Θ(|V|²), or order m + n² [1, 2]. Swapping the list for a more sophisticated data structure such as a binary min-heap speeds up queue extraction and priority updates, bringing the runtime down to O(V log V + E log V), or m + n · log(n) [2, 4].
In 1984, Fredman and Tarjan proposed a Fibonacci heap priority queue, cutting the asymptotic bound to Θ(|E| + |V| log |V|). That remains the fastest known single-source shortest-path bound for arbitrary directed graphs with unbounded non-negative weights. Still, specialized cases such as directed acyclic graphs or networks with bounded integer weights can be improved even further [1].
Bidirectional Search and Highway Hierarchies
Computing distances to every vertex in a graph wastes effort if a program only cares about one destination t. On a graph where each node averages m outgoing edges and t lies n hops from start s, a single-source search may relax roughly m^n edges before reaching t. Running two simultaneous searches—forward from s and backward from t—meets near the middle and relaxes only around 2m^(n/2) edges [4].
The tricky part of bidirectional search is knowing when to stop, as Towers notes in his implementation guide corrected with input from Panagiotis Karras, Ciaperoni Martino, Nassos Katsamanis, and Aristides Gionis. Stopping the moment the forward processed set and backward processed set share a connecting edge can return a suboptimal route. Instead, the algorithm tracks a running best distance μ over connecting edges and terminates only when the sum of the current forward and backward minimums equals or exceeds μ [4].
Continental road networks present an even bigger scaling test, since maps of the USA or Western Europe need an eight-digit number of nodes. In a 2005 paper in Algorithms – ESA 2005, Peter Sanders and Dominik Schultes introduced Highway Hierarchies, which preprocesses eight-digit node maps in a few hours using linear space. Once preprocessed, exact shortest-path queries finish in about 8 milliseconds, running roughly 2,000 times faster than unassisted Dijkstra [5]. Later preprocessing techniques such as contraction hierarchies push query speed-ups up to seven orders of magnitude faster [1].
Testing Dijkstra’s Algorithm in Code
Clean implementations usually separate path computation from path reporting by maintaining two arrays, dist[] and prev[], or equivalent map structures [1, 7]. In pseudocode, removing vertex u with minimum distance from queue Q and checking each neighbor v takes only a few lines, followed by a reverse loop that pushes predecessors onto a stack S to read the route in forward order [1].
A 2016 walkthrough on the Clean Coder Blog explored how Test-Driven Development (TDD) shapes that code structure without hardcoding test inputs. Starting from a MinPathTest suite, the author wrote degenerate checks for an empty graph, a single node, and disconnected graphs lacking a start or end before moving to a single edge of length 1 connecting A to Z. To keep compact test strings like “A1Z” from leaking into the production API, the author separated graph parsing into a helper and built a PathFinder class exposing addEdge, findPath, getLength, and getPath [7].
That exercise followed what the author called the generality rule: as unit tests grow more specific, the underlying implementation must become more general rather than adding special-case branches. Multi-edge tests such as “A1B,B1Z” then drove the step-by-step discovery logic that generalizes to arbitrary weighted graphs [7].
Applications Beyond Road Maps
While road navigation is the classic textbook case, shortest-path routing appears in networking, artificial intelligence, energy, and robotics [1, 8, 9]. In computer networks, OSPF and IS-IS routers build link-state topologies and run the algorithm locally to pick forwarding tables, while AI planners treat uniform-cost search as a variant of best-first search [1]. In electrical engineering, O. G. Swathika and S. Hemamalini reported in a 2016 IEEE Journal of Emerging and Selected Topics in Power Electronics study that a Prim-aided Dijkstra method inside a central protection center lets microgrids locate faults and keep power flowing to most loads on IEEE 21-bus and 40-bus test systems [8].
Autonomous machines adapt the core idea to three-dimensional spaces and moving traffic. In 2020, M. Z. Luo, X. Hou, and J. Yang wrote in IEEE Access that combining Delaunay triangulation with an extended algorithm converts uneven terrain into 2D passable channels for single-robot surface routing [9]. That same year, E. J. Dhulkefl, A. Durdu, and H. Terzıoğlu simulated unmanned aerial vehicles (UAVs) in MATLAB routing around buildings of varying heights in the Konya Journal of Engineering Sciences [10], while H. Bing described directional improvements and node-reduction graphs for urban express traffic in 2022 [11].
Researchers also generalize the label-setting loop when paths must balance competing costs or spectrum rules. In 2023, P. M. d. l. Casas, L. Kraus, A. Sedeño-Noda, and R. Borndörfer introduced the Targeted Multiobjective Dijkstra Algorithm (T-MDA) in Networks, pairing A*-style goal direction with lazy path storage [12]. Separately, Ireneusz Szcześniak, Andrzej Jajszczyk, and Bożena Woźna-Szcześniak described a generic Dijkstra algorithm using the Boost Graph Library in a 2018 arXiv preprint that hasn’t undergone peer review on the preprint server, testing 85,000 simulation runs on 75-vertex Gabriel graphs with roughly a billion searches for elastic optical networks [13]. In a 2022 arXiv preprint, also not peer-reviewed on the preprint server, Szcześniak and Woźna-Szcześniak generalized Bellman’s principle of optimality to prove that generic version correct [14].
- WEBSITE Wikipedia. (n.d.). Dijkstra’s algorithm. [Article Link]
- WEBSITE Herzog, M., Riedl, W. F., & Velden, L. (2014). Dijkstra’s algorithm. Technische Universität München. [Article Link]
- WEBSITE Wikipedia. (n.d.). Dijkstra. [Article Link]
- WEBSITE Towers, M. (2020, May 30). Bidirectional Dijkstra. [Article Link]
- CONFERENCE PAPER Sanders, P., & Schultes, D. (2005). Highway hierarchies hasten exact shortest path queries. In Algorithms – ESA 2005, Lecture Notes in Computer Science (Vol. 3669). Springer. [Article Link]
- ACADEMIC JOURNAL Wayahdi, M. R., Ginting, S. H. N., & Syahputra, D. (2021). Greedy, A-Star, and Dijkstra’s algorithms in finding shortest path. International Journal of Advances in Data and Information Systems, 2(1), 45–52. [Article Link]
- WEBSITE Clean Coder Blog. (2016, October 26). Dijkstra’s algorithm. [Article Link]
- ACADEMIC JOURNAL Swathika, O. G., & Hemamalini, S. (2016). Prims-aided Dijkstra algorithm for adaptive protection in microgrids. IEEE Journal of Emerging and Selected Topics in Power Electronics, 4(4), 1279–1286. [Article Link]
- ACADEMIC JOURNAL Luo, M. Z., Hou, X., & Yang, J. (2020). Surface optimal path planning using an extended Dijkstra algorithm. IEEE Access, 8, 147827–147838. [Article Link]
- ACADEMIC JOURNAL Dhulkefl, E. J., Durdu, A., & Terzıoğlu, H. (2020). Dijkstra algorithm using UAV path planning. Konya Journal of Engineering Sciences, 8, 92–105. [Article Link]
- ACADEMIC JOURNAL Bing, H. (2022). Improvement and application of Dijkstra algorithms. Academic Journal of Computing & Information Science, 5(5). [Article Link]
- ACADEMIC JOURNAL Casas, P. M. d. l., Kraus, L., Sedeño-Noda, A., & Borndörfer, R. (2023). Targeted multiobjective Dijkstra algorithm. Networks, 82(3), 277–298. [Article Link]
- PREPRINT Szcześniak, I., Jajszczyk, A., & Woźna-Szcześniak, B. (2018). Generic Dijkstra for optical networks. arXiv. [Article Link]
- PREPRINT Szcześniak, I., & Woźna-Szcześniak, B. (2022). Generic Dijkstra. arXiv. [Article Link]
Cover image: Andreas F. Borchert / Wikimedia Commons, CC BY-SA 4.0