Skip to main content
Advanced ~15 min read

Dijkstra's Algorithm

Shortest paths when edges have weights, BFS's disciplined cousin that always expands the closest unvisited node first.

Prerequisites: Breadth-First Search, Greedy Algorithms, Heaps & Priority Queues

BFS finds shortest paths by ring-counting hops, but hops are not cost. A road network where one edge is a highway and another is a dirt track needs weights, and suddenly the ring order lies: a 1-hop neighbor down a dirt track may be farther in total than a 3-hop route on highways. Dijkstra's algorithm fixes this by changing one rule: instead of expanding nodes in arrival order (a FIFO queue), always expand the frontier node with the smallest known total distance (a priority queue).

The algorithm maintains a distance estimate for every node, starting at 0 for the source and infinity for everything else. Each iteration: pull the unvisited node with the smallest estimate, it is now provably final, because any other route would have to leave the frontier through an entry that is already no closer, then relax its outgoing edges: if going through this node gives a neighbor a cheaper total, update the neighbor's distance and remember the edge. Repeat until the queue empties. The greedy choice is safe precisely because all weights are non-negative.

The loop, concretely

  1. 1

    Initialize

    dist[source] = 0, dist[everyone else] = ∞. Push (0, source) into a min-priority-queue. dist doubles as the "best known total cost".

  2. 2

    Extract closest

    Pop the node u with the smallest distance in the queue. If it was already finalized, skip (lazy deletion, stale copies linger in the queue). Otherwise mark it final: no path can ever beat the greedy frontier order.

  3. 3

    Relax edges

    For each neighbor v of u: candidate = dist[u] + weight(u, v). If candidate < dist[v], set dist[v] = candidate, record parent[v] = u, and push (candidate, v).

  4. 4

    Repeat / finish

    Stop when the queue empties (all distances final) or as soon as the target is finalized, early exit. Walk parent pointers backwards to reconstruct the actual path.

Priority-queue Dijkstra

dijkstra.js
function dijkstra(graph, source) {          // graph: Map<node, Array<[neighbor, weight]>>
  const dist = new Map(), parent = new Map();
  for (const node of graph.keys()) dist.set(node, Infinity);
  dist.set(source, 0);

  const pq = [[0, source]];                 // [distance, node], min-heap in production
  const done = new Set();

  while (pq.length > 0) {
    pq.sort((a, b) => a[0] - b[0]);         // demo only: real code uses a binary heap
    const [d, u] = pq.shift();
    if (done.has(u)) continue;              // stale entry, skip
    done.add(u);

    for (const [v, w] of graph.get(u) ?? []) {
      if (d + w < dist.get(v)) {            // relaxation: cheaper through u
        dist.set(v, d + w);
        parent.set(v, u);
        pq.push([d + w, v]);
      }
    }
  }
  return { dist, parent };                  // dist = final shortest costs
}

Cost summary

Operation / caseCostNotes
With a binary heapO((V + E) log V)the standard bound
With a naive array scanO(V²)fine (faster!) for dense graphs where E ≈ V²
Negative edge weightsundefinedthe greedy finality proof breaks, use Bellman–Ford, O(V·E)

Relaxation may touch each edge multiple times through stale queue entries; the `done` check makes that harmless but is what turns correctness into the O((V+E) log V) bound.

Practice

Graph: A→B (weight 1), A→C (weight 4), B→C (weight 2). What is dist[C] when Dijkstra finishes from source A?

Reveal explanation

dist[C] = min(4, 1 + 2) = 3. The greedy order matters: C is finalized only after B, so the relaxation through B lands before C would have been locked at 4.

Check your understanding

  1. 1.Why does Dijkstra use a priority queue instead of BFS's plain FIFO queue?
  2. 2.What is the purpose of the parent[] map?
  3. 3.A map app finds the fastest route with travel times as weights, all positive. It needs one query on a 10-million-node road network. Which structure is essential?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going