Graph Algorithm

Dijkstra's
Algorithm

Find the shortest path from a source to every reachable vertex in a weighted graph. A min-heap priority queue and the relaxation step make it O((V+E) log V) — powering Google Maps, routers, and game pathfinding.

How does Dijkstra's algorithm work?

Dijkstra's algorithm finds the shortest path from a start node to every other node in a graph with non-negative edge weights. It repeatedly picks the unvisited node with the smallest known distance (using a priority queue), then relaxes its edges, updating a neighbour if going through this node is shorter. With a binary heap it runs in O((V + E) log V).

function dijkstra(graph, start) {          // graph: { A: [["B", 4], ["C", 1]], … }
  const dist = { [start]: 0 }, visited = new Set();
  const pq = [[0, start]];                   // use a real heap for big graphs
  while (pq.length) {
    pq.sort((a, b) => a[0] - b[0]);
    const [d, node] = pq.shift();
    if (visited.has(node)) continue;
    visited.add(node);
    for (const [next, w] of graph[node] ?? []) {
      if (d + w < (dist[next] ?? Infinity)) { dist[next] = d + w; pq.push([d + w, next]); }
    }
  }
  return dist;
}

Shortest distances — animated

dijkstra(graph, source=A)step 1/4

// Array state

A:0
src
B:∞
[1]
C:∞
[2]
D:∞
[3]
→ Start at A(dist=0). Push neighbours B(4), C(2)

// Pseudocode

1function dijkstra(graph, source):
2 dist = {v: infinity for each v}
3 dist[source] = 0
4 pq = MinHeap() // (distance, vertex)
5 pq.push((0, source))
6 visited = Set()
7 while pq not empty:
8 (d, u) = pq.pop() // smallest dist first
9 if u in visited: continue
10 visited.add(u)
11 for each (v, w) in graph[u].neighbors:
12 if dist[u] + w < dist[v]:
13 dist[v] = dist[u] + w // relax edge
14 pq.push((dist[v], v))
15 return dist

Algorithm walkthrough

1 / 4
1

Initialise distances

Set dist[source] = 0 and dist[all others] = infinity. Push (0, source) into a min-heap priority queue. This represents 'I can reach source for free.'

1 of 4

Pseudocode

dijkstra.pseudo
1function dijkstra(graph, source):
2 dist = {v: infinity for each v}
3 dist[source] = 0
4 pq = MinHeap() // (distance, vertex)
5 pq.push((0, source))
6 visited = Set()
7 while pq not empty:
8 (d, u) = pq.pop() // smallest dist first
9 if u in visited: continue
10 visited.add(u)
11 for each (v, w) in graph[u].neighbors:
12 if dist[u] + w < dist[v]:
13 dist[v] = dist[u] + w // relax edge
14 pq.push((dist[v], v))
15 return dist

Complexity

Time with binary heap — (V+E) log VO(n log n)

Linearithmic time

Space — dist array + priority queueO(n)

Linear time

Relax edge — O(1) check + O(log V) heap pushO(1)

Constant time

⚠️Negative weights — do not use Dijkstra
Dijkstra's greedy assumption is that once a node is popped from the heap its distance is final. A negative-weight edge could later provide a shorter path — invalidating this assumption. Use Bellman-Ford for graphs with negative weights.
🔍Fibonacci heap variant
With a Fibonacci heap the complexity drops to O(E + V log V) — faster for dense graphs. In practice, binary heap Dijkstra is used almost universally due to simpler implementation.

🎯 Quick Check

Dijkstra processes node U and sees edge U→V with weight 3. dist[U]=5, dist[V]=9. Should it relax?

Dijkstra's Algorithm: summary

Key points

  • It doesn't work with negative edge weights; use Bellman–Ford for those.
  • Store each node's predecessor to reconstruct the actual path.
  • A* adds a heuristic (such as straight-line distance) to search towards the goal faster.

Frequently asked questions

›Why doesn't Dijkstra work with negative weights?

It assumes that once a node has the smallest distance, no later path can be shorter. A negative edge discovered later can break that assumption.