progress

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

The order Dijkstra settles nodes

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

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 shows that order.

The graph is directed with nodes 0 .. n-1; edges holds (u, v, w) with positive weights. Implement settle_order(n, edges, src) -> list[tuple[int, int]]: a (node, distance) pair for every node reachable from src, sorted by distance, ties broken by smaller node number (exactly what a heap of (dist, node) tuples gives). 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
A weighted directed graph from node 0: node 2 settles first at distance 1, node 1 at 3 through 2, node 3 at 8 through 1, and node 4 is unreachable.
badges show the settle order and distance; pink edges are where each distance came from
settle_order(3, [(0, 2, 5), (0, 1, 5)], 0)
# [(0, 0), (1, 5), (2, 5)]             equal distances: smaller node first

Up to 5 * 10^4 nodes and 2 * 10^5 edges; parallel edges and self-loops may appear.

⭐ Bonus: a speed test with 50,000 nodes earns a star with a heap instead of a scan for the closest node.

Show hint

push (dist, node); when you pop a node that's 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