VLVisual Learner

Dijkstra's Algorithm

Time: O(V²) array, O((V+E) log V) heapSpace: O(V)Weights must be ≥ 0
–
Pseudocode
1dist[s] ← 0, every other dist ← ∞
2while some vertex is not finished:
3 u ← the unfinished vertex with the smallest dist
4 if dist[u] = ∞: stop // the rest can't be reached
5 mark u finished // its dist can't get smaller now
6 for each edge u → v (weight w) to an unfinished v:
7 if dist[u] + w < dist[v]:
8 dist[v] ← dist[u] + w; prev[v] ← u
Finished
0
Updates
0
vertex being finished∞ → 7tentative distancefinished / shortest-path tree

What is Dijkstra's Algorithm?

Dijkstra's algorithm finds the shortest path from one start vertex to every other vertex in a graph whose edges have non-negative weights, like road lengths or travel times.

It keeps a tentative distance for every vertex. Each round it picks the unfinished vertex with the smallest tentative distance: that distance can never improve any more (any other route would have to go through a vertex that is already farther away), so the vertex is finished. Then it tries to improve its neighbours through it, which is called relaxing an edge.

Always finish the closest unfinished vertex, then relax its edges.

Using the Visualizer

  • • Edit graph slides out the weighted matrix. Tick Directed for one-way roads. Pick the start or click a vertex.
  • • Numbers next to the vertices are their current distances. Yellow = reached, green = finished.
  • • A green edge being drawn is an improvement; a red dashed one is a route that wasn't shorter.
  • • Type a negative weight and Dijkstra refuses: try the same graph on Bellman-Ford.

How It Works

1. Start

Distance 0 for the start, ∞ for everything else.

2. Pick the closest

Choose the unfinished vertex with the smallest distance and mark it finished.

3. Relax its edges

For each edge u → v of weight w: if dist[u] + w < dist[v], update dist[v] and set prev[v] = u.

4. Repeat

Until every reachable vertex is finished. The prev edges form the shortest-path tree.
Why no negative edges? Finishing the closest vertex assumes going further can only cost more. A negative edge breaks that: a longer detour could suddenly come out cheaper after the vertex was already finished.

Implementation

// Dijkstra's algorithm with a simple array scan: O(V^2), good for dense graphs.
// graph[u][v] = weight of edge u -> v (0 = no edge), all weights >= 0
function dijkstra(graph, s) {
  const n = graph.length;
  const dist = Array(n).fill(Infinity);
  const prev = Array(n).fill(-1);
  const done = Array(n).fill(false);
  dist[s] = 0;

  for (let round = 0; round < n; round++) {
    // pick the unfinished vertex with the smallest distance
    let u = -1;
    for (let v = 0; v < n; v++)
      if (!done[v] && (u === -1 || dist[v] < dist[u])) u = v;
    if (dist[u] === Infinity) break;      // the rest is unreachable
    done[u] = true;

    // relax every edge leaving u
    for (let v = 0; v < n; v++) {
      const w = graph[u][v];
      if (w && !done[v] && dist[u] + w < dist[v]) {
        dist[v] = dist[u] + w;
        prev[v] = u;
      }
    }
  }
  return { dist, prev };
}

// With a priority queue (binary heap) it runs in O((V + E) log V):
//   pq.push([0, s]);
//   while (pq.size) { const [d, u] = pq.pop(); if (d > dist[u]) continue; ...relax... pq.push([dist[v], v]); }

Properties & Complexity

Time Complexity

  • • Array scan: O(V²), simplest and best for dense graphs
  • • Binary heap: O((V + E) log V)
  • • Fibonacci heap: O(E + V log V)

Space & Properties

  • • Space: O(V) for dist, prev and the finished flags
  • • Output: distances plus a shortest-path tree
  • • Greedy: each vertex is finished exactly once

Where It Is Used

  • • Maps and GPS: fastest route between places
  • • Network routing: OSPF finds cheapest paths between routers
  • • Games: path finding (A* is Dijkstra plus a hint)
  • • Any "cheapest way" problem with non-negative costs

Limitations

  • • Negative weights: gives wrong answers, use Bellman-Ford
  • • One source: for all pairs, run it V times or use Floyd-Warshall
  • • Explores everywhere: no sense of direction towards a target