Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Graphs/Dijkstra (Weighted Shortest Path)

Learn the pattern · ~15 min

Dijkstra (Weighted Shortest Path)

also called priority-queue shortest path, best-first search

Always settle the closest unsettled node next. With non-negative weights, nothing found later can beat it.

Signalsweighted graph or grid with non-negative costsminimax path (minimise the max edge on the path)maximum probability path (multiply weights <= 1)Learn firstGraph BFS / DFSTop-K Elements
Cheat sheet and practice

Reach for it when you read

  • +Cheapest, fastest or shortest route where edges have different, non-negative costs.
  • +"Minimise the largest step on the path" (effort, water level): Dijkstra with max in place of +.
  • +Grid problems where moving between cells has a cost (height difference, removing an obstacle).
  • +The state needs more than a node (city plus coupon, cell plus breaks left): Dijkstra on (node, state).

Not this one when

  • ×Every step costs the same: plain BFS is simpler and O(V + E).
  • ×Some edges are negative, or you must detect a negative cycle: Bellman-Ford.
  • ×Distances between all pairs on a small graph (n ≤ 400): Floyd-Warshall.

Learn Dijkstra (Weighted Shortest Path)

First, why isn't BFS enough?

In a weighted graph each edge has a cost (time, distance, money). The shortest path is the one with the smallest total cost, not the fewest edges. Here's a directed graph, each edge written from→to (cost):

41215312345
edges: 1→2 (4), 1→3 (1), 3→2 (2), 2→4 (1), 3→4 (5), 4→5 (3). The orange route 1→3→2→4→5 is the cheapest way to 5.

BFS from 1 says node 2 is one edge away, so it would settle 2 at cost 4. But 1 → 3 → 2 costs 1 + 2 = 3. Fewer edges isn't cheaper. Dijkstra's algorithm fixes this, as long as every cost is non-negative (0 or more).

How does Dijkstra spread?

Keep dist[v], the cheapest cost found so far (∞ at the start, 0 for the source), and a min-heap of (cost, node) pairs, so the cheapest pair is always on top. The rule:

Pop the cheapest pair. If its cost is worse than dist already says, it's old: skip it. Otherwise, for each edge u → v (w), if dist[u] + w beats dist[v], lower dist[v], set parent[v] = u and push the new pair.

Lowering dist[v] is called relaxing the edge. From node 1 (dist and parent for nodes 1..5):

pop what happens heap after dist parent
(0, 1) 2 gets 0 + 4 = 4, 3 gets 0 + 1 = 1 (1,3) (4,2) 0 4 1 ∞ ∞ - 1 1 - -
(1, 3) 3→2: 1 + 2 = 3 beats 4, so 2 improves. 3→4: 4 gets 6 (3,2) (4,2) (6,4) 0 3 1 6 ∞ - 3 1 3 -
(3, 2) 2→4: 3 + 1 = 4 beats 6 (4,2) (4,4) (6,4) 0 3 1 4 ∞ - 3 1 2 -
(4, 2) stale: dist[2] is 3, not 4. Skip (4,4) (6,4) same same
(4, 4) 4→5: 5 gets 4 + 3 = 7 (6,4) (7,5) 0 3 1 4 7 - 3 1 2 4
(6, 4) stale: dist[4] is 4. Skip (7,5) same same
(7, 5) no edges out. Heap empty, done empty 0 3 1 4 7 - 3 1 2 4

The pop costs come out in order: 0, 1, 3, 4, 7. Each node's first real pop is at its final cost.

The code for it

C++
vector<long long> dijkstra(int n, int src, vector<vector<pair<int, int>>>& adj, vector<int>& parent) {
    vector<long long> dist(n, LLONG_MAX);
    parent.assign(n, -1);
    priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> pq;   // min-heap
    dist[src] = 0;
    pq.push({0, src});
    while (!pq.empty()) {
        auto [d, u] = pq.top(); pq.pop();
        if (d > dist[u]) continue;           // stale: u was already settled cheaper
        for (auto [v, w] : adj[u])
            if (d + w < dist[v]) {           // relax: a cheaper way to v, through u
                dist[v] = d + w;
                parent[v] = u;
                pq.push({dist[v], v});
            }
    }
    return dist;
}

You don't need to memorise this. It's the table: pop the cheapest, skip it if stale, relax its edges. greater<> is what turns C++'s max-heap into a min-heap.

Why can a node be in the heap twice? The heap can't change a pair already inside it. When 2 improved from 4 to 3, the old (4, 2) stayed in. So we push the new pair and let the old one come out later, where d > dist[u] throws it away.

Fine, but how does this help us?

The classic problem: Network Delay Time. A signal starts at node k and travels directed edges u → v in w time. When have all n nodes received it? If some node never does, return -1.

With the graph above, n = 5 and k = 1, find each node's cheapest arrival by hand:

node cheapest route how you found it arrives at
1 start it's the source 0
3 1→3 the only edge into 3 1
2 1→3→2 1 + 2 = 3 beats the direct 4 3
4 1→3→2→4 3 + 1 = 4 beats 1→3→4 = 6 4
5 1→3→2→4→5 the only edge into 5, after 4 7

Everyone has the signal once the last node does, so the answer is the largest arrival: 7.

The brute force

Without the heap, you can still relax: go over every edge, lower any dist you can, and repeat until a whole pass changes nothing.

C++
int networkDelaySlow(vector<vector<int>>& times, int n, int k) {
    vector<long long> dist(n + 1, LLONG_MAX);
    dist[k] = 0;
    for (bool changed = true; changed; ) {  // repeat until a whole pass changes nothing
        changed = false;
        for (auto& t : times)
            if (dist[t[0]] != LLONG_MAX && dist[t[0]] + t[2] < dist[t[1]])
                dist[t[1]] = dist[t[0]] + t[2], changed = true;
    }
    long long worst = *max_element(dist.begin() + 1, dist.end());
    return worst == LLONG_MAX ? -1 : (int)worst;
}

It's correct, but a pass costs E, and with an unlucky edge order each pass fixes only one more node: up to V passes, O(V · E). LeetCode keeps this problem tiny (n ≤ 100), so it passes there. On CSES Shortest Routes I, V = 10⁵ and E = 2 × 10⁵: a backwards-listed chain needs V passes, about 2 × 10¹⁰ steps, 15 seconds at -O2. Time limit exceeded.

The one thought that fixes it

Stop at the third pop, (3, 2). Could there still be a cheaper way to node 2, one we haven't found?

Any other route must leave the settled nodes (1 and 3) through some edge, landing on a node waiting in the heap. Everything in the heap costs at least 3, since (3, 2) is on top, and every later edge adds 0 or more. So that route costs at least 3 too. The cheapest pair in the heap is final.

So each node is expanded once, when first popped. The brute force kept relaxing edges out of nodes that were already final; the heap names the next final node.

C++
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
    vector<vector<pair<int, int>>> adj(n + 1);     // nodes are 1..n
    for (auto& t : times) adj[t[0]].push_back({t[1], t[2]});
    vector<int> parent;
    vector<long long> dist = dijkstra(n + 1, k, adj, parent);
    long long worst = *max_element(dist.begin() + 1, dist.end());   // the last node to hear it
    return worst == LLONG_MAX ? -1 : (int)worst;
}

Dry run

The run is the first table. At the end:

node 1 2 3 4 5
dist 0 3 1 4 7
parent - 3 1 2 4

The largest dist is 7, the same answer as the brute force. Following parent back from 5 gives the route 1 → 3 → 2 → 4 → 5. From k = 2, no path reaches 1 or 3, so they stay at ∞: -1.

Why it's O(E log V)

Count what happens to each edge: it's relaxed once, when its start node pops for real, and pushes at most one pair. So at most E pushes and pops, each O(log E) = O(log V). O(E log V) time, O(V + E) space.

From O(V · E) down to O(E log V), by always expanding the one node that's already final.

What about negative edges?

The argument above needs "every edge adds 0 or more". With a negative edge it breaks. Take 0→1 (2), 0→2 (3), 2→1 (−2), 1→3 (1):

pop what happens dist[0..3]
(0, 0) 1 gets 2, 2 gets 3 0 2 3 ∞
(2, 1) popped as "final" at 2; 3 gets 3 0 2 3 3
(3, 2) 2→1: 3 − 2 = 1 beats 2. The "final" node improves! Push (1, 1) 0 1 3 3
(1, 1) not stale, so 1 is expanded again: 3 gets 2 0 1 3 2
(2, 3), (3, 3) nothing out of 3; the second is stale 0 1 3 2

So "popped means final" is gone. Our code still ends right, since an improved node gets back in: with negative edges but no negative cycle, it always ends with the correct distances. The catch is time. A node can be re-expanded again and again, and there are graphs where each extra pair of nodes doubles the work: 37 nodes and 54 edges take 786,430 expansions. Exponential.

The version that skips a node once it has been popped (a visited array) is fast but wrong: it never re-expands 1, so dist[3] stays 3. With a negative cycle, ours never stops. So with negative edges, use Bellman-Ford or its queue form, SPFA: O(V · E) at worst, and they detect negative cycles.

Remember this

  • Weighted shortest path, all weights ≥ 0 → Dijkstra. All weights equal → plain BFS. Some negative → Bellman-Ford.
  • Use a min-heap (greater<>) and skip stale pops with d > dist[u].
  • Sum in long long; check for nodes left at ∞.
  • Whenever a problem asks for the cheapest, fastest or safest route where steps cost different amounts, it's this.

Practise it on Network Delay Time, then Path with Maximum Probability (max-heap, multiply), Path With Minimum Effort (max instead of +: extending a path never lowers its worst step), Minimum Obstacle Removal to Reach Corner (costs 0 or 1), Number of Ways to Arrive at Destination (count the ties) and Swim in Rising Water (max again).

Below, watch Network Delay Time run line by line.

Watch it work, line by line

Network Delay Time ↗, n = 5, k = 1, edges 1→2:4 1→3:1 3→2:2 3→4:5 2→4:1 4→5:3 2→5:7 → 7. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

One source (or several), weighted edges that are never negative, and I want the cheapest way to reach things?

Reach for it when

  • +weighted graph or grid with non-negative costs
  • +minimax path (minimise the max edge on the path)
  • +maximum probability path (multiply weights <= 1)
  • +E up to 2e5-1e6 -> O(E log V)

It fails when

  • ×Any edge weight can be negative: nodes get finalized too earlyuse Bellman-Ford
  • ×Unweighted or all weights equaluse Plain BFS
  • ×Weights are only 0 or 1use 0-1 BFS with a deque, O(V+E)
  • ×All-pairs shortest paths on a small dense graphuse Floyd-Warshall
  • ×Limit on edges/stops: pruning on stops breaks optimalityuse Bellman-Ford k rounds, or BFS on (node, stops)

Looks like it, isn't (and the other way round)

  • Path with Maximum Probability looks like Bellman-Ford, needs this pattern

    Multiplying probabilities <= 1 never increases a path's value, so Dijkstra with a max-heap is valid.

  • Path With Minimum Effort looks like Graph BFS / DFS, needs this pattern

    Cost is the max edge on the path: minimax Dijkstra (or binary search + BFS, or union-find).

  • Swim in Rising Water looks like Graph BFS / DFS, needs this pattern

    Minimax over cell heights; plain BFS ignores the cost.

  • Minimum Time to Visit a Cell In a Grid looks like Graph BFS / DFS, needs this pattern

    Arrival times vary per cell and waiting changes time by 2 (back-and-forth), so it is Dijkstra with a parity correction, not BFS.

  • Cheapest Flights Within K Stops looks like Dijkstra (Weighted Shortest Path), needs Bellman-Ford

    The stop limit invalidates per-vertex optimality; k+1 Bellman-Ford rounds (or Dijkstra over (city, stops)).

  • Critical Cities looks like Dijkstra (Weighted Shortest Path), needs Dominator Tree

    The catalog tags it dijkstra, but the question is about all routes, not shortest ones: vertices dominating n from 1.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1Why is a node's distance final the moment it pops from the heap?Reveal

    Every other route to it goes through a node still in the heap, which is at least as far, and non-negative edges can't make it shorter.

  • 2What does if (d > dist[u]) continue; do?Reveal

    Skips stale entries: older, worse times for a node that was later reached faster. It replaces decrease-key.

  • 3When does Dijkstra give wrong answers, and what do you use instead?Reveal

    With negative edge weights, a settled node could later be reached more cheaply. Use Bellman-Ford.

Practice ladder

every problem →
  1. 1Network Delay Timethe hookMedium
  2. 2Shortest Routes Iplain distancesMedium
  3. 3Path with Maximum Probabilitymultiply instead of addMedium
  4. 4Path With Minimum Effortminimise the worst stepMedium
  5. 5Minimum Obstacle Removal to Reach Corner0-1 weightsHard
  6. 6Flight Discountextra state in the nodeMedium
  7. 7Number of Ways to Arrive at Destinationcount the shortest pathsMedium
  8. 8Swim in Rising Waterminimise the worst stepHard

Finished Dijkstra (Weighted Shortest Path)? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Dijkstra (Weighted Shortest Path)

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial