Algorithms · Visualized
Dijkstra's Shortest Path
Graph Algorithms
Traverse, order, and find shortest paths and spanning trees on graphs — the machinery behind maps, networks, schedulers and dependency resolvers.
Dijkstra computes shortest paths from one source in a weighted graph with non-negative weights. Time: O(E log V) average, O(E log V) worst; space: O(V) for distances and the priority queue.
Big-O: Traversals O(V + E); Dijkstra O(E log V) with a heap; Bellman–Ford O(V·E); Floyd–Warshall O(V³); MST O(E log E).
Dijkstra's Shortest Path
Graph AlgorithmsDijkstra computes shortest paths from one source in a weighted graph with non-negative weights. It greedily settles the closest unsettled node — with non-negative edges nothing could later improve that node's distance — then relaxes its outgoing edges. A priority queue makes 'pick the closest' cheap, giving O(E log V).
How Dijkstra's Shortest Path Works
- Set dist[start] = 0 and dist[everyone else] = ∞; push the start into a min-priority queue.
- Pop the node u with the smallest tentative distance; if it is already settled, skip (stale entry).
- Settle u — its distance is now provably final.
- For each neighbour v, relax: if dist[u] + weight(u, v) < dist[v], update dist[v] and push v.
- Repeat until the queue is empty; all reachable nodes end up settled with final distances.
Dijkstra's Shortest Path Worked Example
Input: {graph: A—B(4), A—C(2), B—C(1), B—D(5), C—D(8), C—E(10), D—E(2), D—F(6), E—F(3), start: A}
Settle A(0) → relax B=4, C=2. Settle C(2) → B improves to 3 (2+1), D=10, E=12. Settle B(3) → D improves to 8. Settle D(8) → E improves to 10, F=14. Settle E(10) → F improves to 13. Settle F(13). Distances: A=0 B=3 C=2 D=8 E=10 F=13.
import heapq
def dijkstra(n, edges, start):
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
dist = [float('inf')] * n
dist[start] = 0
pq = [(0, start)] # (distance, node)
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]: # stale entry
continue
for v, w in adj[u]:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
heapq.heappush(pq, (dist[v], v))
return distBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Dijkstra's Shortest Path Time & Space Complexity
When to Use Dijkstra's Shortest Path
- GPS navigation and routing engines with positive travel times.
- Network routing (OSPF uses Dijkstra), shortest latency paths, robot path planning on weighted grids.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.