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.
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
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;
} import heapq
def network_delay_time(times, n, k):
adj = [[] for _ in range(n + 1)]
for u, v, w in times:
adj[u].append((v, w))
dist = [float("inf")] * (n + 1)
dist[k] = 0
pq = [(0, k)] # (distance, node), smallest first
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue # stale entry: u already has a shorter distance
for v, w in adj[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(pq, (dist[v], v))
worst = max(dist[1:])
return worst if worst < float("inf") else -1 int networkDelayTime(vector<vector<int>>& times, int n, int k) {
vector<vector<pair<int, int>>> adj(n + 1); // u -> {v, weight}
for (auto& t : times) adj[t[0]].push_back({t[1], t[2]});
vector<int> dist(n + 1, INT_MAX);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq; // {dist, node}, min first
dist[k] = 0;
pq.push({0, k});
while (!pq.empty()) {
auto [d, u] = pq.top(); pq.pop();
if (d > dist[u]) continue; // stale entry
for (auto [v, w] : adj[u])
if (d + w < dist[v]) { dist[v] = d + w; pq.push({dist[v], v}); }
}
int worst = *max_element(dist.begin() + 1, dist.end());
return worst == INT_MAX ? -1 : worst;
} class MinHeap { // binary heap of [key, ...] arrays
constructor() { this.a = []; }
get size() { return this.a.length; }
push(x) {
const a = this.a;
a.push(x);
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, top = a[0], last = a.pop();
if (a.length) {
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 networkDelayTime(times, n, k) {
const adj = Array.from({ length: n + 1 }, () => []);
for (const [u, v, w] of times) adj[u].push([v, w]);
const dist = new Array(n + 1).fill(Infinity);
const pq = new MinHeap(); // [dist, node]
dist[k] = 0;
pq.push([0, k]);
while (pq.size) {
const [d, u] = pq.pop();
if (d > dist[u]) continue; // stale entry
for (const [v, w] of adj[u])
if (d + w < dist[v]) { dist[v] = d + w; pq.push([dist[v], v]); }
}
const worst = Math.max(...dist.slice(1));
return worst === Infinity ? -1 : worst;
} The variations
-
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.
-
2The path cost is its biggest step
Replace
d + wwithmax(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.Now you solve -
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.
Now you solve -
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.