~/problems / Weighted graphs / Dijkstra (weighted shortest paths)

Basics: the order Dijkstra settles nodes

easy basics ~10 min

Dijkstra's key idea: pop the closest unsettled node from a min-heap. Its distance can never improve after that, so it is settled. This drill asks you to show that order.

The graph is directed with nodes 0 .. n-1, and edges is a list of (u, v, w) with positive weights w (Dijkstra also works with zero weights, but then the tie order below isn't guaranteed). Implement settle_order(n, edges, src) -> list[tuple[int, int]]: return a (node, distance) pair for every node reachable from src, in the order Dijkstra settles them. That is, sorted by distance, with ties broken by the smaller node number (which is exactly what a heap of (dist, node) tuples gives you). Each node appears once, and unreachable nodes are left out.

edges = [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 5), (2, 3, 8)]
settle_order(5, edges, 0)
# [(0, 0), (2, 1), (1, 3), (3, 8)]     node 4 is unreachable

settle_order(3, [(0, 2, 5), (0, 1, 5)], 0)
# [(0, 0), (1, 5), (2, 5)]             equal distances: smaller node first

Constraints: 1 <= n <= 5 * 10^4, up to 2 * 10^5 edges, 1 <= w <= 10^6. Parallel edges and self-loops may appear.

Show hint

push (dist, node) onto a heap; when you pop an entry for a node that is already settled (a stale entry), skip it, otherwise settle it and relax its edges.

Topic: Dijkstra (weighted shortest paths). Heap of (dist, node), skip stale entries; non-negative weights only.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc