Graphs · Pattern 9 of 14

Dijkstra's algorithm: shortest paths with weights

Always expand the closest node not yet settled, using a min-heap. With non-negative weights, the first time a node is popped its distance is final. Skip stale heap entries.

4 variations · 7 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Edges with different non-negative costs or times
  • Cheapest, fastest or least effort path
  • A path cost that is the largest step instead of the sum
  • A limit on stops or discounts, which turns into extra state

The template

Dijkstra
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]});   // u -> {v, weight}
    int[] dist = new int[n + 1];
    Arrays.fill(dist, Integer.MAX_VALUE);
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));   // {dist, node}
    dist[k] = 0;
    pq.offer(new int[]{0, k});
    while (!pq.isEmpty()) {
        int[] top = pq.poll();
        int d = top[0], u = top[1];
        if (d > dist[u]) continue;                  // stale entry: u already has a shorter distance
        for (int[] e : adj.get(u)) {
            int v = e[0], nd = d + e[1];
            if (nd < dist[v]) { dist[v] = nd; pq.offer(new int[]{nd, v}); }
        }
    }
    int worst = 0;
    for (int i = 1; i <= n; i++) worst = Math.max(worst, dist[i]);
    return worst == Integer.MAX_VALUE ? -1 : worst;
}

The variations

  1. 1Classic single-source shortest path

    Push the source with distance 0, pop the closest node, relax its edges. To compare every city, run it from each one (or use Floyd-Warshall for small n) and count the cities within the threshold.

  2. 2The path cost is its biggest step

    Replace d + w with max(d, w): the effort of a route is its steepest step, and the time to swim is the highest cell on the way. The heap still pops the best route first.

  3. 3Extra state in the node

    When there is a limit (stops used, discounts used), the node becomes (city, used). For stops, a Bellman-Ford pass per stop, copying the distances each round, is the simplest correct answer.

  4. 4Waiting rules on the edges

    A cell opens only at a given time. You can wait by stepping back and forth, which costs 2 seconds, so if you arrive too early you round up to the next time with the right parity. That arrival time is the new distance.

Mistakes to avoid

  • Using Dijkstra with negative edge weights: a settled node can still get cheaper. Use Bellman-Ford instead.
  • Not skipping stale heap entries (d > dist[u]): the answer stays right but the run can get much slower.
  • Cheapest flights within k stops: plain Dijkstra on cost can throw away a pricier path that uses fewer stops. Track stops in the state, or run k + 1 rounds of Bellman-Ford.

Mark it done once you can write the template from memory and you have solved the worked examples yourself.