Skip to lesson

Dijkstra algorithm

Dijkstra algorithm greedily computes single-source shortest paths on non-negative weighted graphs in O((V + E) log V) time.

Greedy shortest paths using PriorityQueue

Dijkstra's algorithm finds the shortest paths from one node to all others in a graph with non-negative edge weights, always expanding the closest unvisited node using a priority queue.

Dijkstra algorithm computes shortest paths from a single origin on non-negative weighted graphs. Standard BFS fails because high-weight edges are processed identically to lightweight edges.

Dijkstra uses a greedy strategy powered by a min-heap PriorityQueue. At each step, extract the unvisited vertex with the smallest tentative distance. Because all edge weights are non-negative, this smallest distance is permanently finalised.

Dijkstra step-by-step trace

Step 1 of 5

42158ABCD
distA
0
distB
inf
distC
inf
distD
inf
Start at node A with distance 0. Queue contains A with distance 0.

Initialise dist array with infinity, setting dist[source] = 0. Insert distance and vertex pairs into the PriorityQueue. When vertex u is popped, relax each outgoing edge (u, v, weight). If dist[u] + weight < dist[v], update dist[v] and insert the new pair.

Order of execution

Run Dijkstra

Tap the steps in the order Dijkstra runs them.

Skipping stale entries in Java

Standard Java PriorityQueue does not support an efficient decreaseKey operation. When a shorter distance to node v is found, we push a new pair into the heap. Consequently, the heap can contain multiple duplicate entries for the same vertex.

Example 1 · Brute force: repeat every edge until nothing changes, O(V * E) time, O(V) space

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        int n = 4;        int[][] edges = {{0, 1, 4}, {0, 2, 2}, {2, 1, 1}, {1, 3, 5}, {2, 3, 8}};        int[] dist = new int[n];        Arrays.fill(dist, Integer.MAX_VALUE);        dist[0] = 0;
        int passes = 0;        boolean changed = true;        while (changed) {            changed = false;            passes++;            for (int[] e : edges) {                if (dist[e[0]] != Integer.MAX_VALUE && dist[e[0]] + e[2] < dist[e[1]]) {                    dist[e[1]] = dist[e[0]] + e[2];                    changed = true;                }            }        }        System.out.println("Distances from 0: " + Arrays.toString(dist));        System.out.println("Passes over all edges: " + passes);    }}
Output
Distances from 0: [0, 3, 2, 8]
Passes over all edges: 2

What this code does

  • Every pass re-checks all edges, even edges whose start vertex has not changed.
  • It stops when a full pass changes nothing, so it needs up to V passes of E edges each.
  • The answer is correct but wastes work: that waste is what Dijkstra removes.

Example 2 · Better: scan an array for the closest vertex, O(V^2) time, O(V^2) space

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        int n = 4;        int INF = Integer.MAX_VALUE;        int[][] w = new int[n][n];        for (int[] row : w) Arrays.fill(row, INF);        w[0][1] = 4; w[0][2] = 2; w[2][1] = 1; w[1][3] = 5; w[2][3] = 8;
        int[] dist = new int[n];        Arrays.fill(dist, INF);        dist[0] = 0;        boolean[] done = new boolean[n];
        for (int round = 0; round < n; round++) {            int u = -1;            for (int v = 0; v < n; v++) {          // linear scan for the closest vertex                if (!done[v] && dist[v] != INF && (u == -1 || dist[v] < dist[u])) u = v;            }            if (u == -1) break;            done[u] = true;            for (int v = 0; v < n; v++) {                if (w[u][v] != INF && dist[u] + w[u][v] < dist[v]) dist[v] = dist[u] + w[u][v];            }        }        System.out.println("Distances from 0: " + Arrays.toString(dist));    }}
Output
Distances from 0: [0, 3, 2, 8]

What this code does

  • Each vertex is finalised once, in order of distance, so no edge is re-checked after its start is done.
  • Finding the closest vertex costs a scan of V entries, and that scan runs V times.
  • The next example swaps the scan for a min-heap.

Example 3 · Optimal: Dijkstra with a min-heap, O((V + E) log V) time, O(V) space

Main.javaJava
import java.util.*;
public class Main {    static class Edge {        int to, weight;        Edge(int to, int weight) { this.to = to; this.weight = weight; }    }
    static int[] dijkstra(int n, List<List<Edge>> adj, int src) {        int[] dist = new int[n];        Arrays.fill(dist, Integer.MAX_VALUE);        dist[src] = 0;
        // Min-heap storing [distance, vertex]        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));        pq.offer(new int[]{0, src});
        while (!pq.isEmpty()) {            int[] curr = pq.poll();            int d = curr[0];            int u = curr[1];
            // Prune stale entry            if (d > dist[u]) continue;
            for (Edge e : adj.get(u)) {                int v = e.to;                int w = e.weight;                if (dist[u] + w < dist[v]) {                    dist[v] = dist[u] + w;                    pq.offer(new int[]{dist[v], v});                }            }        }        return dist;    }
    public static void main(String[] args) {        int n = 4;        List<List<Edge>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        adj.get(0).add(new Edge(1, 4));        adj.get(0).add(new Edge(2, 2));        adj.get(2).add(new Edge(1, 1));        adj.get(1).add(new Edge(3, 5));        adj.get(2).add(new Edge(3, 8));
        int[] dist = dijkstra(n, adj, 0);        System.out.println("Distances from 0: " + Arrays.toString(dist));    }}
Output
Distances from 0: [0, 3, 2, 8]

What this code does

  • Min-heap orders vertices by current tentative distance.
  • Stale entries are pruned when d > dist[u] upon polling.
  • Shortest path to vertex 1 goes through vertex 2 with total cost 3.
  • The heap returns the closest vertex in O(log V) instead of an O(V) scan, so a sparse graph costs far less than V * V.

Example 4 · Network Delay Time in Java

Main.javaJava
import java.util.*;
public class Main {    static int networkDelayTime(int[][] times, int n, int k) {        List<List<int[]>> adj = new ArrayList<>();        for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());        for (int[] t : times) {            adj.get(t[0]).add(new int[]{t[1], t[2]});        }
        int[] dist = new int[n + 1];        Arrays.fill(dist, Integer.MAX_VALUE);        dist[k] = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));        pq.offer(new int[]{0, k});
        while (!pq.isEmpty()) {            int[] curr = pq.poll();            int d = curr[0];            int u = curr[1];            if (d > dist[u]) continue;
            for (int[] edge : adj.get(u)) {                int v = edge[0];                int w = edge[1];                if (dist[u] + w < dist[v]) {                    dist[v] = dist[u] + w;                    pq.offer(new int[]{dist[v], v});                }            }        }
        int maxTime = 0;        for (int i = 1; i <= n; i++) {            if (dist[i] == Integer.MAX_VALUE) return -1;            maxTime = Math.max(maxTime, dist[i]);        }        return maxTime;    }
    public static void main(String[] args) {        int[][] times = {{2, 1, 1}, {2, 3, 1}, {3, 4, 1}};        System.out.println("Network delay time: " + networkDelayTime(times, 4, 2));    }}
Output
Network delay time: 2

What this code does

  • Graph uses 1-based indexing for vertices from 1 to n.
  • Signal radiates outwards and max time across all nodes gives total delay.
  • Returns -1 if any node remains unreachable with MAX_VALUE.

Example 5 · Path with Minimum Effort on Grid in Java

Main.javaJava
import java.util.*;
public class Main {    static int minimumEffortPath(int[][] heights) {        int r = heights.length;        int c = heights[0].length;        int[][] effort = new int[r][c];        for (int[] row : effort) Arrays.fill(row, Integer.MAX_VALUE);        effort[0][0] = 0;
        // [effort, row, col]        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));        pq.offer(new int[]{0, 0, 0});
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        while (!pq.isEmpty()) {            int[] curr = pq.poll();            int eff = curr[0];            int cr = curr[1];            int cc = curr[2];            if (eff > effort[cr][cc]) continue;            if (cr == r - 1 && cc == c - 1) return eff;
            for (int[] d : dirs) {                int nr = cr + d[0];                int nc = cc + d[1];                if (nr >= 0 && nr < r && nc >= 0 && nc < c) {                    int diff = Math.abs(heights[nr][nc] - heights[cr][cc]);                    int nextEff = Math.max(eff, diff);                    if (nextEff < effort[nr][nc]) {                        effort[nr][nc] = nextEff;                        pq.offer(new int[]{nextEff, nr, nc});                    }                }            }        }        return 0;    }
    public static void main(String[] args) {        int[][] heights = {            {1, 2, 2},            {3, 8, 2},            {5, 3, 5}        };        System.out.println("Minimum effort path: " + minimumEffortPath(heights));    }}
Output
Minimum effort path: 2

What this code does

  • Effort along a route is the maximum absolute height difference encountered.
  • Dijkstra variant minimises the bottleneck edge weight along the path.
  • Route (0,0)->(0,1)->(0,2)->(1,2)->(2,2) has maximum step difference of 2.

Leaving outdated entries in the heap wastes computation time. Fortunately, we can prune stale entries with a single check upon polling. When polling pair (d, u), check if d > dist[u]. If d exceeds the recorded optimal distance, ignore the pair and continue immediately. This lazy deletion pattern ensures each vertex expands its neighbours at most once. The overall runtime remains optimal at O((V + E) log V).

Find the bug

Spot the Dijkstra bug

Select the line that is wrong.

Stale heap entries should be skipped, but this skips the good ones.

Round 1 of 3

Why negative edge weights break Dijkstra

Dijkstra relies on the assumption that visited nodes have finalised optimal distances. Once a vertex is marked done, its distance is never reconsidered.

A negative edge weight violates this core foundation. A longer path with positive weights might later encounter a massive negative edge. That detour could yield a total cost lower than the greedily finalised distance.

Because Dijkstra never re-evaluates finalised vertices, it returns incorrect distances. Graphs with negative edge weights require the Bellman-Ford algorithm instead. In real-world applications like GPS map routing, road travel costs are strictly non-negative.

Next step

Check your understanding

10 quick questions