Data Structures · Visualization
Graph: Dijkstra
Graph
Dijkstra's algorithm finds the shortest path from a source node to all other nodes in a graph where edges have non-negative weights (costs). Time: O((V + E) log V) with a binary heap priority queue. Space: O(V) for distances and the priority queue.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: Dijkstra
GraphDijkstra's algorithm finds the shortest path from a source node to all other nodes in a graph where edges have non-negative weights (costs). It works greedily: it always expands the closest not-yet-finalized node next, using a priority queue (min-heap) to efficiently pick that node, and updates ('relaxes') the known shortest distance to each of its neighbors if a shorter path is found through it.
How Dijkstra Works
- Set the source node's distance to 0 and every other node's distance to infinity.
- Add all nodes to a min-priority queue, ordered by current known distance.
- Repeatedly extract the node with the smallest distance from the queue.
- For each of its neighbors, check if going through the current node offers a shorter path; if so, update ('relax') that neighbor's distance.
- Repeat until the queue is empty; the recorded distances are the shortest paths from the source.
Dijkstra Worked Example
Input: Graph with weighted edges A-B(4), A-C(1), C-B(1), B-D(1), source = A
- distance: A=0, others=infinity. Extract A (smallest)
- Relax neighbors of A: B=4, C=1
- Extract C (distance 1, smallest). Relax B via C: 1+1=2 < 4, update B=2
- Extract B (distance 2). Relax D via B: 2+1=3, update D=3
- Extract D (distance 3). Done.
Output: Shortest distances from A: B=2, C=1, D=3
Press ▶ Run to watch it step by step.
import heapq
def dijkstra(adj, start):
dist = {v: float('inf') for v in adj}
dist[start] = 0
pq = [(0, start)] # (distance, node)
while pq:
d, v = heapq.heappop(pq)
if d > dist[v]:
continue # stale entry
for nxt, w in adj[v]:
nd = d + w
if nd < dist[nxt]:
dist[nxt] = nd
heapq.heappush(pq, (nd, nxt))
return dist
# example: Dijkstra fromBehind 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 Time & Space Complexity
When to Use Dijkstra
- GPS navigation systems finding the fastest/shortest driving route
- Network routing protocols finding the cheapest path for data
- Flight/travel booking systems finding the cheapest connection
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.