Interactive LabRuns in your browser

Dijkstra Shortest Path

Step-by-step shortest path exploration with relaxation table and priority queue.

Speed:
4215810263ABCDEF
Distance table
Nodedistprevfinal
A—
B—
C—
D—
E—
F—
Priority queue (smallest first)
empty
Pseudocode
1dist[s] = 0; pq = [(0, s)]
2while pq not empty:
3 (d, u) = pq.popMin()
4 if u == target: done
5 for each edge (u, v, w):
6 if d + w < dist[v]:
7 dist[v] = d + w; prev[v] = u
8 pq.push((dist[v], v))

About this tool

Dijkstra’s algorithm finds the shortest path from one source to every other node in a graph with non-negative edge weights. It repeatedly takes the unfinished node with the smallest known distance from a priority queue, marks that distance as final, and relaxes its outgoing edges: if going through it gives a neighbour a shorter distance, the neighbour’s distance and predecessor are updated.

This lab animates every pop and every relaxation on a weighted graph, keeps the distance table and the priority queue visible, and highlights the final shortest path between the source and target you choose.

How to use Dijkstra Shortest Path

  1. Pick a source and a target node.
  2. Press play. Each step either pops the closest node from the queue or relaxes one edge; the status line shows the arithmetic, e.g. 4 + 3 = 7 < 9.
  3. Follow the distance table: “final” marks distances that can no longer change, and “prev” records where each best path came from.
  4. When the target is popped, the shortest path is traced back through the prev column and drawn on the graph.

Examples

A relaxation that improves

Input
dist[B] = 4, edge B→C weight 3, dist[C] = 9
Result
4 + 3 = 7 < 9 → dist[C] = 7, prev[C] = B

A relaxation that does not

Input
dist[D] = 5, edge D→C weight 4, dist[C] = 7
Result
5 + 4 = 9 is not shorter → keep 7

Implementation in five languages

The same algorithm in Python, JavaScript, Java, Go and C++. Each program is complete and runnable; the comments show what it prints.

import heapq

graph = {
    "A": [("B", 4), ("C", 2)],
    "B": [("D", 5)],
    "C": [("B", 1), ("D", 8)],
    "D": [("E", 3)],
    "E": [],
}


def dijkstra(source):
    dist = {node: float("inf") for node in graph}
    prev = {}
    dist[source] = 0
    pq = [(0, source)]
    while pq:
        d, node = heapq.heappop(pq)
        if d > dist[node]:
            continue                      # stale queue entry
        for nxt, w in graph[node]:
            if d + w < dist[nxt]:         # relax the edge
                dist[nxt] = d + w
                prev[nxt] = node
                heapq.heappush(pq, (dist[nxt], nxt))
    return dist, prev


def path(prev, target):
    out = [target]
    while out[-1] in prev:
        out.append(prev[out[-1]])
    return out[::-1]


dist, prev = dijkstra("A")
print(dist)              # {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 11}
print(path(prev, "E"))   # ['A', 'C', 'B', 'D', 'E']
const graph = {
  A: [['B', 4], ['C', 2]],
  B: [['D', 5]],
  C: [['B', 1], ['D', 8]],
  D: [['E', 3]],
  E: [],
};

// Minimal binary heap of [distance, node] pairs.
class MinHeap {
  constructor() { this.a = []; }
  get size() { return this.a.length; }
  push(item) {
    const a = this.a;
    a.push(item);
    for (let i = a.length - 1; i > 0;) {
      const p = (i - 1) >> 1;
      if (a[p][0] <= a[i][0]) break;
      [a[p], a[i]] = [a[i], a[p]];
      i = p;
    }
  }
  pop() {
    const a = this.a;
    const top = a[0];
    const last = a.pop();
    if (a.length > 0) {
      a[0] = last;
      for (let i = 0; ;) {
        const l = 2 * i + 1, r = l + 1;
        let m = i;
        if (l < a.length && a[l][0] < a[m][0]) m = l;
        if (r < a.length && a[r][0] < a[m][0]) m = r;
        if (m === i) break;
        [a[m], a[i]] = [a[i], a[m]];
        i = m;
      }
    }
    return top;
  }
}

function dijkstra(source) {
  const dist = Object.fromEntries(Object.keys(graph).map((n) => [n, Infinity]));
  const prev = {};
  dist[source] = 0;
  const pq = new MinHeap();
  pq.push([0, source]);
  while (pq.size > 0) {
    const [d, node] = pq.pop();
    if (d > dist[node]) continue; // stale queue entry
    for (const [next, w] of graph[node]) {
      if (d + w < dist[next]) { // relax the edge
        dist[next] = d + w;
        prev[next] = node;
        pq.push([dist[next], next]);
      }
    }
  }
  return { dist, prev };
}

function path(prev, target) {
  const out = [target];
  while (prev[out[0]] !== undefined) out.unshift(prev[out[0]]);
  return out;
}

const { dist, prev } = dijkstra('A');
console.log(dist); // { A: 0, B: 3, C: 2, D: 8, E: 11 }
console.log(path(prev, 'E').join(' → ')); // A → C → B → D → E
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeMap;

public class Main {
    record Edge(String to, int weight) {}
    record Entry(int dist, String node) {}

    static final Map<String, List<Edge>> GRAPH = Map.of(
        "A", List.of(new Edge("B", 4), new Edge("C", 2)),
        "B", List.of(new Edge("D", 5)),
        "C", List.of(new Edge("B", 1), new Edge("D", 8)),
        "D", List.of(new Edge("E", 3)),
        "E", List.of()
    );

    public static void main(String[] args) {
        Map<String, Integer> dist = new TreeMap<>();
        Map<String, String> prev = new HashMap<>();
        for (String n : GRAPH.keySet()) dist.put(n, Integer.MAX_VALUE);
        dist.put("A", 0);

        PriorityQueue<Entry> pq = new PriorityQueue<>((x, y) -> Integer.compare(x.dist(), y.dist()));
        pq.add(new Entry(0, "A"));
        while (!pq.isEmpty()) {
            Entry e = pq.poll();
            if (e.dist() > dist.get(e.node())) continue;   // stale queue entry
            for (Edge edge : GRAPH.get(e.node())) {
                int nd = e.dist() + edge.weight();
                if (nd < dist.get(edge.to())) {             // relax the edge
                    dist.put(edge.to(), nd);
                    prev.put(edge.to(), e.node());
                    pq.add(new Entry(nd, edge.to()));
                }
            }
        }

        System.out.println(dist);  // {A=0, B=3, C=2, D=8, E=11}
        LinkedList<String> path = new LinkedList<>(List.of("E"));
        while (prev.containsKey(path.getFirst())) path.addFirst(prev.get(path.getFirst()));
        System.out.println(path);  // [A, C, B, D, E]
    }
}
package main

import (
	"container/heap"
	"fmt"
	"math"
)

type Edge struct {
	To     string
	Weight int
}

var graph = map[string][]Edge{
	"A": {{"B", 4}, {"C", 2}},
	"B": {{"D", 5}},
	"C": {{"B", 1}, {"D", 8}},
	"D": {{"E", 3}},
	"E": {},
}

// Item and PQ implement container/heap's interface.
type Item struct {
	Dist int
	Node string
}
type PQ []Item

func (q PQ) Len() int           { return len(q) }
func (q PQ) Less(i, j int) bool { return q[i].Dist < q[j].Dist }
func (q PQ) Swap(i, j int)      { q[i], q[j] = q[j], q[i] }
func (q *PQ) Push(x any)        { *q = append(*q, x.(Item)) }
func (q *PQ) Pop() any {
	old := *q
	it := old[len(old)-1]
	*q = old[:len(old)-1]
	return it
}

func dijkstra(source string) (map[string]int, map[string]string) {
	dist := map[string]int{}
	prev := map[string]string{}
	for n := range graph {
		dist[n] = math.MaxInt
	}
	dist[source] = 0
	pq := &PQ{{0, source}}
	for pq.Len() > 0 {
		it := heap.Pop(pq).(Item)
		if it.Dist > dist[it.Node] {
			continue // stale queue entry
		}
		for _, e := range graph[it.Node] {
			if nd := it.Dist + e.Weight; nd < dist[e.To] { // relax the edge
				dist[e.To] = nd
				prev[e.To] = it.Node
				heap.Push(pq, Item{nd, e.To})
			}
		}
	}
	return dist, prev
}

func main() {
	dist, prev := dijkstra("A")
	fmt.Println(dist) // map[A:0 B:3 C:2 D:8 E:11]

	path := []string{"E"}
	for p, ok := prev[path[0]]; ok; p, ok = prev[path[0]] {
		path = append([]string{p}, path...)
	}
	fmt.Println(path) // [A C B D E]
}
#include <algorithm>
#include <climits>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <utility>
#include <vector>

using Graph = std::map<std::string, std::vector<std::pair<std::string, int>>>;

const Graph graph = {
    {"A", {{"B", 4}, {"C", 2}}},
    {"B", {{"D", 5}}},
    {"C", {{"B", 1}, {"D", 8}}},
    {"D", {{"E", 3}}},
    {"E", {}},
};

int main() {
    std::map<std::string, int> dist;
    std::map<std::string, std::string> prev;
    for (const auto& [node, edges] : graph) dist[node] = INT_MAX;
    dist["A"] = 0;

    using Item = std::pair<int, std::string>;  // (distance, node)
    std::priority_queue<Item, std::vector<Item>, std::greater<Item>> pq;
    pq.push({0, "A"});
    while (!pq.empty()) {
        auto [d, node] = pq.top();
        pq.pop();
        if (d > dist[node]) continue;              // stale queue entry
        for (const auto& [next, w] : graph.at(node)) {
            if (d + w < dist[next]) {              // relax the edge
                dist[next] = d + w;
                prev[next] = node;
                pq.push({dist[next], next});
            }
        }
    }

    for (const auto& [node, d] : dist) std::cout << node << '=' << d << ' ';
    std::cout << '\n';                             // A=0 B=3 C=2 D=8 E=11

    std::vector<std::string> path = {"E"};
    while (prev.count(path.back())) path.push_back(prev[path.back()]);
    std::reverse(path.begin(), path.end());
    for (const auto& n : path) std::cout << n << ' ';
    std::cout << '\n';                             // A C B D E
}

Practice on LeetCode

Classic problems that use this algorithm. Try them after working through the lab. Links open on LeetCode.

Why it works — and when it does not

When a node is popped, every other unfinished node is at least as far away, and since weights are non-negative no later path can be shorter. A single negative edge breaks this argument; use Bellman–Ford for graphs with negative weights.

Complexity

  • With a binary heap: O((V + E) log V).
  • With a plain array and no heap: O(V²), which is competitive for very dense graphs.
  • Stopping as soon as the target is popped saves work for single-pair queries; A* goes further by adding a distance estimate to the target.

Frequently asked questions

Everything you need to know about this tool and data security.

Why can a node appear in the queue more than once?

This “lazy” version pushes a new entry whenever a distance improves instead of updating it in place. Stale entries are skipped when popped because the node is already final.

Is the result a tree?

Yes. The prev pointers form a shortest-path tree rooted at the source, giving the best path to every reachable node at once.

Where is Dijkstra used?

Routing protocols such as OSPF and IS-IS, map navigation (usually with A* and preprocessing), network latency planning, and many game AI pathfinding systems.

Is my data safe when using this tool?

Yes, 100% safe. This tool operates entirely inside your web browser using client-side JavaScript and WebAssembly. Your data never touches any external server.