CoursifyCoursify

Dijkstra's Algorithm

Dijkstra's Algorithm

Verified Sources
May 19, 2026

Dijkstra's Algorithm solves the single-source shortest path problem: given a weighted graph and a source vertex, it computes the minimum path cost from the source to every reachable vertex, provided all edge weights are nonnegative.2 The algorithm is a classic greedy algorithm because it repeatedly selects the unsettled vertex with the smallest known tentative distance and permanently settles it.2

A useful way to view the method is through relaxation: for each edge (u,v)(u,v) with weight w(u,v)w(u,v), we test whether going through uu improves the current estimate for vv:

dist[v]min(dist[v],dist[u]+w(u,v)).\text{dist}[v] \leftarrow \min(\text{dist}[v], \text{dist}[u] + w(u,v)).

This local update rule, combined with the nonnegative-edge assumption, yields globally correct shortest-path distances.2

Dijkstra's algorithm is foundational in route planning, network routing, and many graph-processing systems. For example, it underlies shortest-route computation in transportation networks and is used in routing protocols such as OSPF and IS-IS.

Footnotes

  1. Dijkstra's algorithm - Wikipedia - Overview of the algorithm, applications, and implementation complexity.

  2. Dijkstra Algorithm Explained: Why It Actually Works | Codeintuition - Clear explanation of the greedy invariant and why nonnegative weights are required. 2 3

  3. Dijkstra’s Algorithm with a Priority Queue - Practical walkthrough of heap-based implementation and stale-entry handling.

  4. 1 Non-negative weights - László Kozma - Lecture notes covering relaxation, invariants, and correctness reasoning.

  5. Dijkstra's algorithm - Wikipedia - Notes on applications including route planning, OSPF, IS-IS, and use as a subroutine.

Dijkstra's algorithm in 3 minutes

Core Applicability Condition

Dijkstra's algorithm is correct only when all edge weights are nonnegative. If negative edges are present, the greedy settlement step can become invalid.2

Footnotes

  1. Dijkstra Algorithm Explained: Why It Actually Works | Codeintuition - Clear explanation of the greedy invariant and why nonnegative weights are required.

  2. Dijkstra's Algorithm - GeeksforGeeks - Explanation of why negative weights invalidate Dijkstra's correctness argument.

Problem setting and intuition

Let G=(V,E)G=(V,E) be a weighted graph, directed or undirected. We choose a source vertex ss and seek the shortest-path distance δ(s,v)\delta(s,v) to each vertex vVv \in V.2 The algorithm maintains:

  • a tentative distance array dist\text{dist}
  • an optional predecessor array parent\text{parent} for path reconstruction
  • a min-priority queue keyed by current tentative distance2

Initially,

dist[s]=0,dist[v]= for vs.\text{dist}[s]=0, \qquad \text{dist}[v]=\infty \text{ for } v\neq s.

At each iteration, the minimum-distance unsettled vertex is extracted. Because all remaining edges are nonnegative, no future path can improve that extracted value; therefore the distance becomes final.2

This is the central invariant:

InvariantMeaningWhy it matters
Tentative distances are upper boundsdist[v]δ(s,v)\text{dist}[v] \ge \delta(s,v) never becomes too smallPrevents invalid underestimation
Extracted minimum is finalOnce vertex uu is removed from the queue, dist[u]=δ(s,u)\text{dist}[u]=\delta(s,u)Gives correctness of the greedy choice2
Relaxation propagates improvementsBetter paths discovered through settled vertices update neighborsBuilds shortest paths incrementally2

The algorithm may stop early if only a single target is needed: once that target is extracted from the queue, its shortest distance is known.

Footnotes

  1. Dijkstra's algorithm - Wikipedia - Overview of the algorithm, applications, and implementation complexity. 2

  2. 1 Non-negative weights - László Kozma - Lecture notes covering relaxation, invariants, and correctness reasoning. 2 3

  3. Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 - GeeksforGeeks - Complexity discussion for adjacency lists, binary heaps, and Fibonacci heaps. 2

  4. Dijkstra Algorithm Explained: Why It Actually Works | Codeintuition - Clear explanation of the greedy invariant and why nonnegative weights are required. 2 3

  5. Dijkstra's Algorithm - GeeksforGeeks - Explanation of why negative weights invalidate Dijkstra's correctness argument.

  6. Dijkstra's algorithm - Wikipedia - Notes on applications including route planning, OSPF, IS-IS, and use as a subroutine.

How Dijkstra's Algorithm Executes

  1. 1
    Step 1

    Set the source distance to 0 and every other vertex to ∞. Initialize a predecessor array if path reconstruction is required.2

    Footnotes

    1. Dijkstra's algorithm - Wikipedia - Overview of the algorithm, applications, and implementation complexity.

    2. Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 - GeeksforGeeks - Complexity discussion for adjacency lists, binary heaps, and Fibonacci heaps.

  2. 2
    Step 2

    Store vertices keyed by their current tentative distances. In practical implementations, a binary heap is common because it supports efficient extract-min and update operations.2

    Footnotes

    1. Dijkstra's algorithm - Wikipedia - Overview of the algorithm, applications, and implementation complexity.

    2. Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 - GeeksforGeeks - Complexity discussion for adjacency lists, binary heaps, and Fibonacci heaps.

  3. 3
    Step 3

    Remove the unsettled vertex with minimum tentative distance. This vertex is now considered settled, meaning its shortest-path distance is final under the nonnegative-weight assumption.2

    Footnotes

    1. Dijkstra Algorithm Explained: Why It Actually Works | Codeintuition - Clear explanation of the greedy invariant and why nonnegative weights are required.

    2. Dijkstra's Algorithm - GeeksforGeeks - Explanation of why negative weights invalidate Dijkstra's correctness argument.

  4. 4
    Step 4

    For every edge from the extracted vertex to a neighbor, test whether the path through the extracted vertex is shorter. If so, update the neighbor's distance and predecessor, then adjust its priority in the queue.2

    Footnotes

    1. Dijkstra Algorithm Explained: Why It Actually Works | Codeintuition - Clear explanation of the greedy invariant and why nonnegative weights are required.

    2. 1 Non-negative weights - László Kozma - Lecture notes covering relaxation, invariants, and correctness reasoning.

  5. 5
    Step 5

    Continue until the queue is empty, or terminate earlier if a specific destination has just been extracted. At that point, all settled vertices have correct shortest distances.2

    Footnotes

    1. Dijkstra's algorithm - Wikipedia - Notes on applications including route planning, OSPF, IS-IS, and use as a subroutine.

    2. Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 - GeeksforGeeks - Complexity discussion for adjacency lists, binary heaps, and Fibonacci heaps.

Worked example

Consider the weighted graph below with source AA.

Initialization gives:

  • dist[A]=0\text{dist}[A]=0
  • dist[B]=\text{dist}[B]=\infty
  • dist[C]=\text{dist}[C]=\infty
  • dist[D]=\text{dist}[D]=\infty
  • dist[E]=\text{dist}[E]=\infty

After relaxing edges from AA, we get:

  • dist[B]=4\text{dist}[B]=4
  • dist[C]=1\text{dist}[C]=1

Next, CC is extracted because it has the smallest tentative distance. Relaxing from CC improves BB from 44 to 33, and sets DD to 66.2 Then BB is extracted with distance 33, which improves DD to 44. Finally, DD improves EE to 77.

Final shortest distances from AA are:

VertexShortest distance from AAOne shortest path
A0A
B3A → C → B
C1A → C
D4A → C → B → D
E7A → C → B → D → E

This example illustrates why repeated relaxation plus greedy extraction is effective: the shortest-path tree emerges incrementally as better paths are discovered and finalized.2

Footnotes

  1. Dijkstra’s Algorithm with a Priority Queue - Practical walkthrough of heap-based implementation and stale-entry handling. 2 3

  2. Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 - GeeksforGeeks - Complexity discussion for adjacency lists, binary heaps, and Fibonacci heaps.

  3. Dijkstra Algorithm Explained: Why It Actually Works | Codeintuition - Clear explanation of the greedy invariant and why nonnegative weights are required.

Why Negative Edges Break the Algorithm

If a vertex is settled too early, a later path that includes a negative edge could reduce its distance. That contradicts Dijkstra's key invariant that extracted distances are final.2

Footnotes

  1. Dijkstra Algorithm Explained: Why It Actually Works | Codeintuition - Clear explanation of the greedy invariant and why nonnegative weights are required.

  2. Dijkstra's Algorithm - GeeksforGeeks - Explanation of why negative weights invalidate Dijkstra's correctness argument.

Correctness: why the greedy choice works

The correctness argument depends on a simple but powerful property. Suppose vertex uu is the unsettled vertex with smallest tentative distance. If all edge weights are nonnegative, then any alternative path to uu through another unsettled vertex must have length at least dist[u]\text{dist}[u] plus some nonnegative amount, so it cannot be shorter.2 Hence:

when u is extracted, dist[u]=δ(s,u).\text{when } u \text{ is extracted, } \text{dist}[u] = \delta(s,u).

This proof is often expressed as a loop invariant or induction argument. The two central claims are:

  1. Tentative distances never underestimate true shortest distances.
  2. Each extracted vertex has the correct final distance.2

Once claim 2 holds for the current extraction, relaxing outgoing edges preserves claim 1 and allows the frontier of known shortest paths to expand safely.

A concise conceptual summary is:

Footnotes

  1. Dijkstra Algorithm Explained: Why It Actually Works | Codeintuition - Clear explanation of the greedy invariant and why nonnegative weights are required. 2 3

  2. 1 Non-negative weights - László Kozma - Lecture notes covering relaxation, invariants, and correctness reasoning. 2 3 4

1import heapq 2 3 4def dijkstra(graph, source): 5 dist = {v: float('inf') for v in graph} 6 parent = {v: None for v in graph} 7 dist[source] = 0 8 pq = [(0, source)] 9 10 while pq: 11 curr_dist, u = heapq.heappop(pq) 12 13 if curr_dist != dist[u]: 14 continue 15 16 for v, w in graph[u]: 17 new_dist = curr_dist + w 18 if new_dist < dist[v]: 19 dist[v] = new_dist 20 parent[v] = u 21 heapq.heappush(pq, (new_dist, v)) 22 23 return dist, parent

Data structures and complexity

The efficiency of Dijkstra's algorithm depends strongly on the graph representation and priority-queue implementation.3

  • With an adjacency list and a binary heap, the time complexity is typically O((V+E)logV)O((V+E)\log V), often written as O(ElogV)O(E\log V) for connected sparse graphs.3
  • With an adjacency matrix and linear scanning for the next minimum, the complexity is O(V2)O(V^2).2
  • With a Fibonacci heap, the theoretical bound can improve to O(E+VlogV)O(E + V\log V), though binary heaps are often preferred in practice because of simpler implementation and lower constants.

Space usage is usually O(V+E)O(V+E) when the graph is stored as an adjacency list, plus storage for distances, predecessors, and queue state.2

For sparse graphs, adjacency-list implementations are generally much more practical than matrix-based versions.2

Footnotes

  1. Dijkstra's algorithm - Wikipedia - Overview of the algorithm, applications, and implementation complexity. 2 3

  2. Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 - GeeksforGeeks - Complexity discussion for adjacency lists, binary heaps, and Fibonacci heaps. 2 3 4 5

  3. A Complete Guide to Dijkstra's Shortest Path Algorithm | Codecademy - Summary of time and space complexity under common graph representations. 2 3 4

  4. Dijkstra’s Algorithm with a Priority Queue - Practical walkthrough of heap-based implementation and stale-entry handling.

Typical Time Complexity by Implementation

Relative asymptotic cost of common Dijkstra implementations.3

Footnotes

  1. Dijkstra's algorithm - Wikipedia - Overview of the algorithm, applications, and implementation complexity.

  2. Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 - GeeksforGeeks - Complexity discussion for adjacency lists, binary heaps, and Fibonacci heaps.

  3. A Complete Guide to Dijkstra's Shortest Path Algorithm | Codecademy - Summary of time and space complexity under common graph representations.

Common Questions and Edge Cases

Practical applications and limitations

Dijkstra's algorithm appears in many real systems because shortest-path computation is a fundamental abstraction for optimization over networks.

Major application areas

Application areaGraph interpretationOptimization goal
Road navigationIntersections as vertices, roads as weighted edgesShortest or fastest route
Network routingRouters as vertices, links as weighted edgesLowest-cost forwarding path
Infrastructure planningFacilities and connections as weighted graph componentsLeast-cost connectivity analysis
Algorithm designSubroutine inside larger methods such as Johnson's algorithmRepeated shortest-path computation

However, Dijkstra has important limitations:

  1. It does not support negative-weight edges safely.2
  2. On very large graphs, naïve implementations can be too slow.2
  3. It computes shortest paths from one source; it is not itself an all-pairs shortest-path algorithm.2

In practice, the algorithm remains one of the most important building blocks in graph theory, routing protocols, and pathfinding because of its strong correctness guarantee and efficient performance on nonnegative weighted graphs.2

Footnotes

  1. Dijkstra's algorithm - Wikipedia - Notes on applications including route planning, OSPF, IS-IS, and use as a subroutine. 2 3 4 5 6 7

  2. Dijkstra Algorithm Explained: Why It Actually Works | Codeintuition - Clear explanation of the greedy invariant and why nonnegative weights are required. 2

  3. Dijkstra's Algorithm - GeeksforGeeks - Explanation of why negative weights invalidate Dijkstra's correctness argument.

  4. Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 - GeeksforGeeks - Complexity discussion for adjacency lists, binary heaps, and Fibonacci heaps.

  5. A Complete Guide to Dijkstra's Shortest Path Algorithm | Codecademy - Summary of time and space complexity under common graph representations.

  6. Dijkstra's algorithm - Wikipedia - Overview of the algorithm, applications, and implementation complexity.

Implementation Best Practice

In heap-based implementations, use a stale-entry check such as if popped_distance != dist[u]: continue to ignore outdated queue entries after a shorter path has already been found.

Footnotes

  1. Dijkstra’s Algorithm with a Priority Queue - Practical walkthrough of heap-based implementation and stale-entry handling.

Knowledge Check

Question 1 of 4
Q1Single choice

What problem does Dijkstra's algorithm solve?

Explore Related Topics

1

The Banker's Algorithm: Deadlock Avoidance in Operating Systems

The Banker's Algorithm is a deadlock‑avoidance method that keeps a system in a safe state by checking each resource request against the maximum declared needs of processes.

  • Maintains Available, Max, Allocation, and Need matrices, where Need[i][j]=Max[i][j]Allocation[i][j]\text{Need}[i][j]=\text{Max}[i][j]-\text{Allocation}[i][j].
  • The Safety Algorithm uses vectors Work and Finish to find an execution order; if all processes finish, the state is safe.
  • The Resource‑Request Algorithm simulates allocation, runs the safety check, and commits only if the resulting state remains safe.
  • Time complexity of the safety check is O(m×n2)O(m \times n^{2}).
  • In practice the algorithm is rarely used because processes must predeclare maximum needs and the algorithm’s overhead is high.
2

Graph Traversals: Breadth-First Search (BFS) vs. Depth-First Search (DFS)

This content contrasts Breadth‑First Search (BFS) and Depth‑First Search (DFS), outlining their traversal order, complexity, and typical use cases.

  • BFS uses a FIFO queue, visits nodes level by level (A→B→C→D→E→F); DFS uses a LIFO stack, dives deep (A→B→D→E→C→F).
  • Both run in O(V+E)O(V+E) time; BFS may need O(V)O(V) (or O(bd)O(b^d)) space, while DFS typically uses O(d)O(d) stack depth.
  • BFS guarantees the shortest path in unweighted graphs, suited for routing, web crawling, and level‑order serialization.
  • DFS excels in memory‑limited, wide graphs and in tasks like topological sort and cycle detection, but deep recursion can cause stack overflow.
3

Minimum Spanning Tree (MST) and Prim's Algorithm

Prim's algorithm builds a minimum spanning tree (MST) of a connected weighted undirected graph by repeatedly adding the cheapest edge that links the current tree to a new vertex.

  • An MST includes all VV vertices, has exactly V1V-1 edges, contains no cycles, and minimizes total edge weight.
  • The cut property guarantees that the lightest edge crossing any cut (the current tree vs. the rest) is safe to include in an MST.
  • Algorithm steps: start at any vertex, repeatedly select the minimum‑weight crossing edge, add its outside vertex, and update candidate edges until all vertices are reached.
  • With an adjacency list and a priority queue, the runtime is O(ElogV)O(E \log V); using an adjacency matrix it is O(V2)O(V^2).
  • In the example graph, Prim selects edges AB(2),BC(1),BD(4),CE(6)AB(2), BC(1), BD(4), CE(6), producing an MST of total weight 1313.
Chat with Kiro