Shortest paths in a DAG
About this lesson
When a weighted graph has no directed cycle, you do not need Dijkstra's heap or Bellman-Ford's repeated rounds. Sort the nodes topologically, then relax the arrows out of each node exactly once, in that order. Watch it run on six places with one negative arrow, and see why a single pass gives the exact cheapest cost in O(V + E) time. The lessons "Topological sort" and "Bellman-Ford and negative edges" cover the two ideas this one combines.
Arrows with costs
Six places joined by one-way arrows. Each arrow has a cost, its weight: S to A costs 2. B to C costs −2, a refund. No loop of arrows, so this is a DAG. Goal: the cheapest total cost from S to every place.
a weighted DAG: one-way arrows, no directed cycle
the cost of a path = the sum of its arrow weights
S -> A 2
S -> B 6
A -> B 3
A -> C 7
B -> C −2
C -> D 1
C -> T 2
D -> T 3
in Python, each node lists (next node, weight) pairs:
graph = {
"S": [("A", 2), ("B", 6)],
"A": [("B", 3), ("C", 7)],
"B": [("C", -2)],
"C": [("D", 1), ("T", 2)],
"D": [("T", 3)],
"T": [],
}Read the lesson step by step
Arrows with costs
Six places joined by one-way arrows. Each arrow has a cost, its weight: S to A costs 2. B to C costs −2, a refund. No loop of arrows, so this is a DAG. Goal: the cheapest total cost from S to every place.
a weighted DAG: one-way arrows, no directed cycle the cost of a path = the sum of its arrow weights S -> A 2 S -> B 6 A -> B 3 A -> C 7 B -> C −2 C -> D 1 C -> T 2 D -> T 3 in Python, each node lists (next node, weight) pairs: graph = { "S": [("A", 2), ("B", 6)], "A": [("B", 3), ("C", 7)], "B": [("C", -2)], "C": [("D", 1), ("T", 2)], "D": [("T", 3)], "T": [], }Line them up first
First, a topological sort lists the places so every arrow points forward: S, A, B, C, D, T. Here every arrow points left to right. So when we reach a place, every arrow into it starts at a place we have already passed.
topological order: S A B C D T every arrow u -> v has u earlier in the list: S (#1) -> A (#2) S (#1) -> B (#3) A (#2) -> B (#3) A (#2) -> C (#4) B (#3) -> C (#4) C (#4) -> D (#5) C (#4) -> T (#6) D (#5) -> T (#6) preds = node -> nodes with arrows into it order = list(TopologicalSorter(preds).static_order())Start: 0 here, ∞ elsewhere
Each place keeps dist: the cheapest cost found so far. S costs 0 to reach from itself. Every other place starts at ∞ (infinity), meaning no path found yet. These numbers only ever go down.
dist = {u: math.inf for u in graph} dist["S"] = 0 S 0 · A ∞ · B ∞ · C ∞ · D ∞ · T ∞ dist[v] is always the cost of some real path to v (or ∞), so it can only be too high, never too lowRelax the arrows out of S
Visit S. For each arrow out, ask: is dist[S] plus the weight cheaper than the far end’s dist? 0 + 2 = 2 beats ∞, so A becomes 2. 0 + 6 = 6 beats ∞: B becomes 6. This check is relaxing an arrow.
for v, w in graph["S"]: if dist["S"] + w < dist[v]: dist[v] = dist["S"] + w S -> A: 0 + 2 = 2 vs ∞ dist[A] = 2 S -> B: 0 + 6 = 6 vs ∞ dist[B] = 6A finds a cheaper B
Visit A, whose dist is 2. Going on to B costs 2 + 3 = 5, cheaper than the 6 from the direct arrow, so B drops to 5 and remembers A as its parent. C gets 2 + 7 = 9 for now.
u = A, dist[A] = 2 A -> B: 2 + 3 = 5 vs 6 dist[B] = 5 A -> C: 2 + 7 = 9 vs ∞ dist[C] = 9 parent[B] = A (the last step of the best path to B)A negative arrow helps
Visit B, now 5. Its only arrow costs −2: 5 + (−2) = 3, cheaper than 9. C drops to 3. The longer path S, A, B, C is cheaper than the short one through A alone. The order makes the negative weight safe.
u = B, dist[B] = 5 B -> C: 5 + −2 = 3 vs 9 dist[C] = 3 best path to C so far: S -> A -> B -> C (2 + 3 − 2 = 3) the direct route S -> A -> C costs 9C reaches D and T
Visit C, now 3. Both arrows into C were already relaxed, so 3 is final. C sends 3 + 1 = 4 to D and 3 + 2 = 5 to T. Both beat ∞.
u = C, dist[C] = 3 (final: arrows A -> C and B -> C are done) C -> D: 3 + 1 = 4 vs ∞ dist[D] = 4 C -> T: 3 + 2 = 5 vs ∞ dist[T] = 5Not every try wins
Visit D, now 4. Its arrow to T gives 4 + 3 = 7, but T already has 5. 7 is not cheaper, so T keeps 5. Visiting T relaxes nothing: it has no arrows out. One pass, and we are done.
u = D, dist[D] = 4 D -> T: 4 + 3 = 7 vs 5 no change u = T: no arrows out dist: S 0 · A 2 · B 5 · C 3 · D 4 · T 5Why one pass is enough
The cheapest path to any place v arrives from some place u before v in the order. By the time we visit v, u was final and its arrow to v was relaxed. So dist[v] is final too. The parent arrows trace each best path.
claim: when the loop reaches v, dist[v] is the true cheapest cost proof by induction along the order: the best path to v ends with some arrow u -> v u is earlier, so dist[u] is already exact relaxing u -> v set dist[v] <= dist[u] + w = the best cost and dist[v] is never below a real path cost, so it is equal A 2 via S -> A B 5 via S -> A -> B C 3 via S -> A -> B -> C D 4 via S -> A -> B -> C -> D T 5 via S -> A -> B -> C -> TLinear time: O(V + E)
The topological sort is O(V + E). Then each place is visited once and each arrow relaxed once: 6 visits, 8 relaxations. Total O(V + E). Bellman-Ford needs O(V·E) for any graph; Dijkstra needs no negative weights.
V = 6 visits, E = 8 relaxations, each O(1) topological sort: O(V + E) total: O(V + E) single-source shortest paths (MIT 6.006 L11): DAG relaxation DAGs only, any weights O(V + E) Bellman-Ford any graph, any weights O(V·E) Dijkstra any graph, weights >= 0 O(V log V + E)
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01dist[u] = 4, dist[v] = 9, and the arrow u → v has weight −2. What does relaxing it do?
4 + (−2) = 2, and 2 < 9, so dist[v] drops to 2 and parent[v] becomes u. Relaxing only ever changes the far end of the arrow.
02Why must the nodes be visited in topological order?
In topological order every arrow points forward. By the time we visit v, every node with an arrow into v was visited and relaxed, so dist[v] can no longer change.
03In the lesson's graph, C first gets dist 9 (via A), then 3. Which arrow lowers it to 3?
dist[B] = 5 after A → B. Then B → C gives 5 + (−2) = 3 < 9. The path S → A → B → C has more arrows but costs less.
04What is the running time of DAG shortest paths on V nodes and E arrows?
The topological sort is O(V + E); then each node is visited once and each arrow relaxed once at O(1) each. MIT 6.006 and Sedgewick and Wayne both give linear time.
05Why can a negative weight not break this algorithm the way it breaks Dijkstra's?
Dijkstra trusts the closest node first, which a later negative arrow can undercut. Here the trust comes from the topological order, not from distances, and with no cycle no path can loop to get cheaper forever.
Glossary
- DAG
- Directed acyclic graph: one-way arrows and no way to follow arrows back to where you started.
- Weight
- The cost written on an arrow. The cost of a path is the sum of its weights. Weights may be negative.
- Topological order
- A list of all the nodes in which every arrow u → v has u earlier than v. Only DAGs have one.
- dist[v]
- The cheapest cost found so far from the source to v. It starts at ∞ and only goes down.
- Relax
- Test one arrow u → v: if dist[u] + w < dist[v], set dist[v] = dist[u] + w and parent[v] = u.
- Parent
- The node just before v on the best path found. Following parents back from v traces the path.
- O(V + E)
- Linear time: work proportional to the number of nodes V plus the number of arrows E.
Notes and sources
- This is DAG relaxation from MIT 6.006 Lecture 11, AcyclicSP in Sedgewick and Wayne §4.4, and DAG-SHORTEST-PATHS in CLRS §22.2 (4th ed.; §24.2 in the 3rd). All three relax the arrows of each node in topological order and run in O(V + E) time.
- Negative weights are fine here because a DAG has no cycle: no path can loop back to make itself cheaper again and again. Bellman-Ford handles negative weights on any graph, at O(V·E) cost.
- The test is strictly less than (<). A tie keeps the first parent found; the cost is the same either way.
- The code is real Python 3.9 or later. It prints the dist and parent dicts. math.inf behaves as infinity: math.inf + w is still math.inf, so an unreached node never lowers its neighbours.
- Start every dist at minus infinity and flip the test to greater than, and the same pass finds longest paths in a DAG. Sedgewick and Wayne use this to schedule jobs (the critical path method). This only works because a DAG has no cycle.
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 11: Weighted Shortest Paths (DAG Relaxation)
- Sedgewick and Wayne, Algorithms 4th ed., §4.4 Shortest Paths (AcyclicSP)
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §22.2
- Python docs: graphlib, TopologicalSorter
- Python docs: math.inf
Quiz Unlocks after the last step.