Dijkstra’s Algorithm Explained: Shortest-Path Example, Pseudocode and Complexity
Learn how Dijkstra’s algorithm works on non-negative weighted graphs, with a worked example, implementation guidance and common mistakes.

Dijkstra’s Algorithm Explained: Shortest-Path Example, Pseudocode and Complexity
Dijkstra’s algorithm computes shortest-path distances from one starting vertex to other reachable vertices in a weighted graph, provided edge weights are non-negative. It is used in routing, network analysis, maps and many graph problems.
A reliable explanation should distinguish the algorithm’s established guarantee from claims about newer research: Dijkstra’s algorithm itself is a classic method, not a new 2025 invention.
Quick facts
| Property | Detail |
|---|---|
| Problem | Single-source shortest paths |
| Graph | Directed or undirected, weighted |
| Edge-weight requirement | Non-negative weights |
| Typical efficient implementation | Adjacency list plus min-priority queue |
| Common complexity | (O((V+E)\log V)) with a binary heap, often simplified to (O(E\log V)) for connected sparse graphs |
| Not suitable as-is for | Graphs with negative-weight edges |
Here, (V) is the number of vertices and (E) is the number of edges.
1. The core idea
The algorithm keeps a tentative distance from the source to every vertex. Initially, the source distance is zero and all other distances are infinity. Repeatedly select the unsettled vertex with the smallest tentative distance, then try to improve the distances of its neighbours.
This improvement step is called relaxation. For an edge from (u) to (v) with weight (w), compare the current distance to (v) with the distance to (u) plus (w):
[
d[v] \leftarrow \min(d[v], d[u] + w)
]
When all weights are non-negative, the smallest unsettled distance is final when selected, which is the key property behind Dijkstra’s correctness.
2. Worked example
Consider these undirected weighted edges:
| Edge | Weight |
|---|---|
| A–B | 4 |
| A–C | 1 |
| C–B | 2 |
| B–D | 1 |
| C–D | 5 |
Find shortest distances from A.
- Start with (d(A)=0); all other distances are infinity.
- Visit A. Set B to 4 and C to 1.
- Visit C, the smallest tentative distance (1). Through C, B improves from 4 to 3, and D becomes 6.
- Visit B (3). Through B, D improves from 6 to 4.
- Visit D (4). No better route is found.
| Vertex | Shortest distance from A | One shortest path |
|---|---|---|
| A | 0 | A |
| C | 1 | A → C |
| B | 3 | A → C → B |
| D | 4 | A → C → B → D |
The algorithm stores predecessors as distances improve. Following those predecessors backwards reconstructs a path.
3. Pseudocode using a min-priority queue
function dijkstra(graph, source):
for each vertex v:
dist[v] = infinity
previous[v] = undefined
dist[source] = 0
priority_queue.push((0, source))
while priority_queue is not empty:
(distance, u) = priority_queue.pop_min()
if distance != dist[u]:
continue // ignore an outdated queue entry
for each edge (u, v, weight) in graph[u]:
candidate = dist[u] + weight
if candidate < dist[v]:
dist[v] = candidate
previous[v] = u
priority_queue.push((candidate, v))
return dist, previousThe outdated-entry check is useful when the priority queue does not support decrease-key directly. The pseudocode assumes all edge weights are non-negative.
4. Time and space complexity
With an adjacency list and binary heap, the usual time bound is (O((V+E)\log V)), and graph plus auxiliary storage is (O(V+E)). An implementation using a simple array to select the next vertex can take (O(V^2)), which may be reasonable for dense graphs or small inputs.
Complexity depends on the data structures and graph representation. State which implementation is being analysed rather than presenting one bound as universal.
5. When not to use Dijkstra’s algorithm
- Unweighted graphs: Breadth-first search (BFS) is simpler and runs in (O(V+E)).
- Negative edge weights: Use Bellman–Ford when negative weights may occur; it can also detect reachable negative cycles.
- All-pairs shortest paths: Floyd–Warshall or repeated single-source methods may fit, depending on graph size and density.
- Very large road networks: Specialized methods such as bidirectional search or contraction-based routing can improve query speed, but involve additional preprocessing and assumptions.
A negative cycle makes a finite shortest path undefined for paths that can repeatedly exploit that cycle. Dijkstra’s usual correctness guarantee does not cover negative edges.
6. Common implementation mistakes
- Using Dijkstra on negative-weight edges.
- Forgetting to initialise the source distance to zero.
- Updating neighbours using the old distance rather than the newly selected distance.
- Treating an unreachable vertex’s infinity value as a real route.
- Forgetting to store predecessors when paths, not just distances, are required.
- Confusing directed and undirected edge representations.
- Reporting complexity without saying which priority-queue implementation is used.
7. What about a “2025 breakthrough”?
A date in an article title should not imply that the core algorithm was invented or fundamentally replaced in 2025. Research on shortest paths continues to study theoretical bounds, specialized graph structures and practical routing systems. To describe a particular 2025 breakthrough accurately, identify the paper or authors, state exactly which problem setting it addresses, and compare its assumptions and results with prior work. Do not label a result as a general replacement for Dijkstra without that evidence.
Frequently asked questions
Does Dijkstra find the shortest path or only the distance?
It computes distances. If the implementation stores predecessors, it can also reconstruct shortest paths.
Can it handle a directed graph?
Yes. Process only the outgoing edges of each vertex. For an undirected graph, represent each edge in both directions.
Why must edge weights be non-negative?
The algorithm finalises the smallest tentative distance when a vertex is selected. A later negative edge could invalidate that decision.
Is a priority queue required?
No, but it makes selecting the next smallest tentative distance efficient. A simple array implementation is also valid and can be suitable for small or dense graphs.
Conclusion
Dijkstra’s algorithm is a dependable single-source shortest-path method for graphs with non-negative weights. Understand relaxation, select the right graph representation, handle unreachable vertices correctly, and choose an alternative when negative weights or a different shortest-path problem changes the requirements.
Further reading
Wipidia Editorial Review Board
✓ Fact-Checked & VerifiedThis article was authored and reviewed by Wipidia's technical editorial desk in Jalandhar, Punjab. Every code snippet, algorithm breakdown, and strategic framework is independently tested against live production standards before publication.

