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

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

  1. Set the source node's distance to 0 and every other node's distance to infinity.
  2. Add all nodes to a min-priority queue, ordered by current known distance.
  3. Repeatedly extract the node with the smallest distance from the queue.
  4. For each of its neighbors, check if going through the current node offers a shorter path; if so, update ('relax') that neighbor's distance.
  5. 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

  1. distance: A=0, others=infinity. Extract A (smallest)
  2. Relax neighbors of A: B=4, C=1
  3. Extract C (distance 1, smallest). Relax B via C: 1+1=2 < 4, update B=2
  4. Extract B (distance 2). Relax D via B: 2+1=3, update D=3
  5. Extract D (distance 3). Done.

Output: Shortest distances from A: B=2, C=1, D=3

Graph: Introduction
A set of nodes connected by edges — edges can be one-way or two-way, and optionally carry a weight (cost/distance).
A
B
C
D
E
Unvisited Visited / discovered Current Start
Graph: Introduction
Press ▶ Run to watch it step by step.
Python · Graphs in Code
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 from
Input: Graph with weighted edges A-B(4), A-C(1), C-B(1), B-D(1), source = A

Behind 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

TimeO((V + E) log V) with a binary heap priority queue
SpaceO(V) for distances and the priority queue

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.