Menu
Coddy logo textTech

Dijkstra's Algorithm

Last updated

Dijkstra's algorithm finds the shortest path from a source node to every other node in a graph with non-negative edge weights. It keeps a tentative distance for each node, repeatedly settles the unsettled node with the smallest tentative distance, and relaxes its edges - updating a neighbor's distance whenever a shorter route through the current node is found. Press play above to watch distances drop as each node is settled.

The key insight is greedy: once the nearest unsettled node is picked, its distance is final, because all other routes to it would have to pass through a node that is already farther away. With a binary-heap priority queue, Dijkstra runs in O((V + E) log V) time. It requires non-negative weights - use Bellman-Ford if edges can be negative.

Time & space complexity

ImplementationComplexityNotes
Binary heapO((V + E) log V)The common, practical choice
Array scanO(V²)Simpler; fine for dense graphs
SpaceO(V)Distances + priority queue
RequiresNon-negative weightsNegative edges break the greedy choice

Step by step

StepWhat happens
1Set the source distance to 0 and all others to infinity.
2Pick the unsettled node with the smallest tentative distance.
3Mark it settled - its shortest distance is now final.
4For each neighbor, compute distance-through-current + edge weight.
5If that is smaller than the neighbor's current distance, relax it.
6Repeat until all reachable nodes are settled.

Worked example

Shortest paths from source A on the graph with edges A-B=4, A-C=1, C-B=2, C-D=5, B-D=1:

StepSettleDistancesAction
0-A=0, B=∞, C=∞, D=∞Initialize: source A=0, all others infinity.
1A (0)B=4, C=1, D=∞Relax edges from A: set B=4, C=1.
2C (1)B=3, D=6Through C: B=1+2=3 beats 4; D=1+5=6.
3B (3)D=4Through B: D=3+1=4 beats 6.
4D (4)A=0, C=1, B=3, D=4Settle D; nothing left to relax. Done.

When to use Dijkstra's algorithm

Use it whenAvoid it when
All edge weights are non-negativeAny edge can be negative - use Bellman-Ford
You need shortest paths from one source to all nodesYou need all-pairs shortest paths - Floyd-Warshall is simpler
The graph is weighted and you want exact distancesThe graph is unweighted - plain BFS is faster and simpler
You have a good heap/priority-queue availableYou want to reach a single target fast with a heuristic - use A*

Dijkstra's Algorithm code

A clean, runnable Dijkstra's Algorithm implementation in Python, JavaScript, Java, C++, C. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Dijkstra's Algorithm code in Python

Python
1import heapq2
3
4def dijkstra(graph, start):5    dist = {node: float("inf") for node in graph}6    dist[start] = 07    pq = [(0, start)]8    while pq:9        d, node = heapq.heappop(pq)10        if d > dist[node]:11            continue  # stale entry, a shorter path was already found12        for neighbor, weight in graph[node]:13            new_dist = d + weight14            if new_dist < dist[neighbor]:15                dist[neighbor] = new_dist16                heapq.heappush(pq, (new_dist, neighbor))17    return dist18
19
20graph = {21    "A": [("B", 4), ("C", 1)],22    "B": [("D", 1)],23    "C": [("B", 2), ("D", 5)],24    "D": [("E", 3)],25    "E": [],26}27
28for node, d in dijkstra(graph, "A").items():29    print(f"A -> {node}: {d}")
Run this code in the Python Playground

Dijkstra's Algorithm FAQ

What is the time complexity of Dijkstra's algorithm?
With a binary-heap priority queue it runs in O((V + E) log V). A simple version that scans an array for the minimum each step is O(V²), which can actually be faster on dense graphs. Both use O(V) space.
Why doesn't Dijkstra work with negative edge weights?
Dijkstra assumes that once it settles the closest unsettled node, that distance is final. A negative edge could later create a shorter path to an already-settled node, breaking that assumption. For graphs with negative weights, use the Bellman-Ford algorithm.
What is the difference between Dijkstra and BFS?
BFS finds shortest paths counting edges (each edge weight is effectively 1), using a plain queue. Dijkstra generalizes this to weighted graphs by always expanding the node with the smallest total distance, using a priority queue. On an unweighted graph the two produce the same paths.
What is the difference between Dijkstra and A* search?
A* is Dijkstra plus a heuristic that estimates the remaining distance to a target, so it steers the search toward that goal instead of expanding uniformly in all directions. When the heuristic is zero, A* degenerates into exactly Dijkstra. Use A* when you have a single destination and a good admissible heuristic; use Dijkstra when you need distances to every node.
When should I use Dijkstra instead of Bellman-Ford?
Use Dijkstra whenever all edge weights are non-negative - it is faster at O((V + E) log V) versus Bellman-Ford's O(V·E). Choose Bellman-Ford only when edges can be negative or you need to detect negative cycles. On non-negative graphs Dijkstra is almost always the better choice.
Can Dijkstra revisit a node after it has been settled?
No - once a node is settled, its distance is final and it is never relaxed again. A common gotcha in heap implementations is leaving stale entries in the priority queue after a node's distance improves; you must skip a popped node if it is already settled (its popped distance exceeds its recorded distance). Forgetting this check still yields correct answers but wastes work.
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED