Skip to the workspace
Pebellslearn by building
Shortest Paths at Scale  ›  Lesson

Shortest Paths on a DAG

Shortest Paths on a DAG 26 minRelax in topological order and every cost settles exactly once

dsa / Shortest Paths on a DAG

Explore each scene at your own pace.

01 · Where Dijkstra goes wrong

Where Dijkstra goes wrong

Shortest Paths on a DAG

Definition
On a directed acyclic graph, shortest paths from a source can be found by relaxing each node's outgoing edges once, in topological order. It takes O(V + E) time and works even when edge weights are negative.
In plain words
If every road only goes forward, you can price each stop in order: by the time you reach a stop, every road into it has already been considered. No stop ever needs a second look, so the order does all the work.

In short: on a directed acyclic graph (DAG) — where legs only ever point "forward", with no way back to a stop already visited — one sweep in topological order finds every cheapest cost, even with negative edges, in O(V + E). Process stops in an order where every leg into a stop comes from an earlier stop, and by the time you reach a stop every leg that could lower its cost has already run. No heap, no settling order to argue about: the order itself is the proof.

Six stops laid out left to right in topological order, each badge settling once as legs point only forward, including one negative-cost leg from quay to yard

Meridian has a model of the city. This section routes things through it and builds the router, starting with the night timetable. After midnight, shuttles run between depots on fixed times, and time only moves forward, so no chain of shuttles can bring you back to where you started. The timetable is a directed acyclic graph, a DAG.

The twist: some legs carry return freight that Meridian is paid for, so on the books they have a negative cost, a credit. You saw a negative edge fool Dijkstra in the graphs section. On a DAG you don't need Dijkstra at all: one sweep through the stops, in the right order, finds every cheapest cost, credits included, in O(V + E).

Where Dijkstra goes wrong

Dijkstra settles the cheapest unsettled stop and never looks at it again. The promise behind that is "nothing found later can be cheaper", and a credit breaks it. Here the mill is settled at 2, but the route through the quay reaches it for 5 − 4 = 1:

What does this print?
import heapq

legs = {"depot": [("mill", 2), ("quay", 5)], "quay": [("mill", -4)],
        "mill": [("harbour", 3)], "harbour": []}
settled = set()
best = {"depot": 0}
heap = [(0, "depot")]
while heap:
    cost, stop = heapq.heappop(heap)
    if stop in settled:
        continue
    settled.add(stop)
    for nxt, step in legs[stop]:
        if nxt not in settled and cost + step < best.get(nxt, float("inf")):
            best[nxt] = cost + step
            heapq.heappush(heap, (cost + step, nxt))
print(best["harbour"])

Dijkstra guessed which stop was final from costs. With no cycles there is a better source of truth: the order of the stops.

Scene 1 of 11
Project context and further resources
You're building a piece ofMeridian — the router
This piece — dag_route(): Finds the cheapest run through the one-way night timetable in a single sweep, credits and all.
Scenario Meridian's night shuttles run on a timetable that only moves forward in time, and some legs pay the van back for carrying return freight. The timetable router finds the cheapest run through that one-way network in a single sweep, credits and all.
dag_route.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
dag_route(legs, start, goal) → dictThe cheapest route through an acyclic timetable as {cost, path}; cost None and an empty path if unreachable.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.