Wipidia
programming•Updated: 24/10/2026•18 views

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.

By Wipidia Editorial Desk•Fact-Checked & Peer-Reviewed
Dijkstra’s Algorithm Explained: Shortest-Path Example, Pseudocode and Complexity
Dijkstra’s algorithm finds shortest paths from a source vertex in a graph with non-negative edge weights. This guide explains relaxation, a worked example, priority-queue pseudocode, time complexity and when to choose BFS, Bellman–Ford or another method.

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

PropertyDetail
ProblemSingle-source shortest paths
GraphDirected or undirected, weighted
Edge-weight requirementNon-negative weights
Typical efficient implementationAdjacency 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 forGraphs 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:

EdgeWeight
A–B4
A–C1
C–B2
B–D1
C–D5

Find shortest distances from A.

  1. Start with (d(A)=0); all other distances are infinity.
  2. Visit A. Set B to 4 and C to 1.
  3. Visit C, the smallest tentative distance (1). Through C, B improves from 4 to 3, and D becomes 6.
  4. Visit B (3). Through B, D improves from 6 to 4.
  5. Visit D (4). No better route is found.
VertexShortest distance from AOne shortest path
A0A
C1A → C
B3A → C → B
D4A → C → B → D

The algorithm stores predecessors as distances improve. Following those predecessors backwards reconstructs a path.

3. Pseudocode using a min-priority queue

text
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, previous

The 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

  1. Using Dijkstra on negative-weight edges.
  2. Forgetting to initialise the source distance to zero.
  3. Updating neighbours using the old distance rather than the newly selected distance.
  4. Treating an unreachable vertex’s infinity value as a real route.
  5. Forgetting to store predecessors when paths, not just distances, are required.
  6. Confusing directed and undirected edge representations.
  7. 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

Tags:#Dijkstra Algorithm#Graph Algorithms#Shortest Path#Data Structures#Pseudocode#Computer Science

Wipidia Editorial Review Board

✓ Fact-Checked & Verified

This 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.