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

Capstone: Meridian's Router

50 minLook at the network, then pick the algorithm it deserves

dsa / Capstone: Meridian's Router

Explore each scene at your own pace.

01 · The decision, in order

The decision, in order

Capstone: Meridian's Router

Definition
A shortest-path router inspects its graph and picks the cheapest algorithm that is still correct: a topological sweep if there are no cycles, Bellman-Ford if any edge is negative, breadth-first search if all weights are equal, and Dijkstra otherwise.
In plain words
Like a driver choosing the right tool for the job, the router first looks at what kind of map it has been handed. A simple map gets a simple, fast method, and only a tricky one gets the heavier method.

In short: no single shortest-path algorithm is right for every network — each one trades correctness for speed differently. A router should classify the network it's handed (no cycles? any negative costs? all costs equal?) and run the cheapest algorithm that is still correct, checking from cheapest to most expensive so a fast, safe answer is never skipped in favour of a slow, safe one. Kahn's algorithm answers "any cycles?" for free, as a side effect of trying to find a topological order.

A flowchart: no cycle leads to sweep, any negative leads to Bellman-Ford, all equal leads to BFS, and the final fallthrough leads to Dijkstra

You now have five ways to find a cheapest route, and each is the right answer to a different question:

The network The algorithm Cost Lesson
no cycles (time only moves forward) topological sweep O(V + E) 1
cycles and negative costs Bellman-Ford, with a loop check O(V × E) 2
every pair, small and dense Floyd–Warshall O(V³) 3
one query, known goal, a map A* far fewer expansions 4
one long query, known goal search from both ends about 2·b^(d/2) 5

and the two you started with: BFS when every road costs the same, and Dijkstra when costs are non-negative. That's the whole shortest-path toolkit, and the skill that remains is choosing. Pick too weak a tool and you get a wrong answer (Dijkstra on rebates). Pick too strong a tool and you're slow (Bellman-Ford on a street map).

This capstone builds the piece that chooses: route_query(roads, start, goal), the single entry point to Meridian's router. It looks at the network it has been handed, picks the cheapest algorithm that is still correct for it, runs it, and reports which one it used.

The decision, in order

The checks run from cheapest to most expensive algorithm:

  1. No cycles at all? Use the topological sweep. It's the fastest correct algorithm there is, and credits don't bother it, so this check comes first even if some costs are negative.
  2. Any negative cost? Then (with cycles present) only Bellman-Ford is correct, and it must check for money-making loops.
  3. Every cost the same? BFS order is cheapest order, and the cost is hops × that weight.
  4. Otherwise costs are non-negative and mixed: Dijkstra.

Kahn's algorithm answers the first question for free: if it emits every stop, there is no cycle. Watch the router classify the night timetable, then the same network with one return road added:

watch it move · graph

If Kahn's algorithm emits every stop there is no cycle and the sweep is safe; one return road leaves every stop waiting, and the router must fall back.

Each badge counts the roads into a stop. Only the depot waits on nothing. 4 nodes, 4 edges, directed. Frontier: depot. depot: 0, mill: 1, quay: 1, harbour: 2.

1 / 6

The set of costs answers the other two:

python

The order of the checks is a policy, and it matters:

What does this print?
roads = [["depot", "mill", -1], ["mill", "quay", -1], ["quay", "harbour", -1]]
out = {"depot": ["mill"], "mill": ["quay"], "quay": ["harbour"], "harbour": []}
waiting = {"depot": 0, "mill": 1, "quay": 1, "harbour": 1}
ready, emitted = ["depot"], 0
while ready:
    n = ready.pop()
    emitted += 1
    for nxt in out[n]:
        waiting[nxt] -= 1
        if waiting[nxt] == 0:
            ready.append(nxt)
costs = {c for _, _, c in roads}
if emitted == len(out):
    print("dag")
elif min(costs) < 0:
    print("bellman-ford")
else:
    print("bfs" if len(costs) == 1 else "dijkstra")

Reversing the first two checks would still give correct answers, only slower. Other reorderings are not safe: checking "all costs equal" before "any negative" would send a network where every road costs −1 to BFS, which would happily report a cost when the true answer is "no cheapest route exists".

What does this print?
roads = [["depot", "mill", -1], ["mill", "depot", -1], ["mill", "harbour", -1]]
costs = {c for _, _, c in roads}
if len(costs) == 1:
    print("bfs")
elif min(costs) < 0:
    print("bellman-ford")

Step through the set logic that the last two checks rest on:

step through it
1roads = [["depot", "mill", 2], ["mill", "depot", 2], ["mill", "quay", 2]]
2costs = set()
3for a, b, c in roads:
4 costs.add(c)
5negative = min(costs) < 0
6uniform = len(costs) == 1
7print(costs, negative, uniform)
Scene 1 of 8
Project context and further resources
You're building a piece ofMeridian — the router
This piece — route_query(): Looks at the network, picks the cheapest correct algorithm, and answers the query.
Scenario Everything comes together in one entry point. A query arrives, the router looks at the network it is being asked about, picks the cheapest algorithm that is still correct for it, and answers, or says plainly why no answer exists.
route_query.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
route_query(roads, start, goal) → dictClassifies the network, runs the matching algorithm, and returns {method, cost, path}.
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.