Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Build the systems
EXPERIMENT 64 / 66

Build a route worth taking.

Combine graph modelling, a priority queue, reconstruction, and testable edge cases.

BY NAVAN SAMI◷ 12 MIN READSTRETCHPROJECT

01 Model the idea

A route engine needs more than a shortest-distance number. Define the graph’s direction, weight units, endpoint policy, unreachable result, and tie behaviour. This project returns both cost and a route using Dijkstra with nonnegative costs. A counter makes equal-cost heap entries safe for arbitrary comparable priorities without depending on vertex-object ordering.

THE THING THAT MUST STAY TRUE

Each parent edge witnesses the currently recorded best route to its child.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
VALIDATE graph assumptions
FIND the cheapest distance through a priority queue
RECONSTRUCT from parent references
VERIFY path edges and total

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

route_engine.py
import heapq
from itertools import count
def route(graph, start, goal):
    if start not in graph or goal not in graph: raise KeyError("Known endpoints required")
    if any(weight < 0 for neighbours in graph.values() for _, weight in neighbours):
        raise ValueError("Nonnegative costs required")
    serial, best, parent = count(), {start: 0}, {start: None}
    queue = [(0, next(serial), start)]
    while queue:
        cost, _, node = heapq.heappop(queue)
        if cost != best[node]: continue
        if node == goal:
            path = []
            while node is not None: path.append(node); node = parent[node]
            return cost, list(reversed(path))
        for neighbour, weight in graph[node]:
            candidate = cost + weight
            if candidate < best.get(neighbour, float("inf")):
                best[neighbour], parent[neighbour] = candidate, node
                heapq.heappush(queue, (candidate, next(serial), neighbour))
    return None
graph = {"A": [("B", 4), ("C", 1)], "C": [("B", 2)], "B": [], "Z": []}
print(route(graph, "A", "B"))
print(route(graph, "A", "Z"))
↳ EXPECTED OUTPUT
(3, ['A', 'C', 'B'])
None
  1. 1

    The parent map changes only when a strictly cheaper route is found. That gives a coherent reconstruction chain.

  2. 2

    The input check rejects negative costs before an early goal return could hide one elsewhere in the supplied graph. All referenced neighbours should also be declared vertices in a production input validator.

  3. 3

    Test the returned route against the original edges and independently sum its cost. An expected final number alone can miss an invalid reconstruction.

04 Count the cost

TIME

O((V + E) log V) on simple graphs

SPACE

O(V + E) state and queued candidates

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Use the same route engine to verify same-endpoint and unreachable behaviour, then check a returned path’s summed edge costs.

Reveal one possible solution +
one_possible_solution.py
import heapq
from itertools import count
def route(graph, start, goal):
    if start not in graph or goal not in graph: raise KeyError("Known endpoints required")
    if any(weight < 0 for neighbours in graph.values() for _, weight in neighbours):
        raise ValueError("Nonnegative costs required")
    serial, best, parent = count(), {start: 0}, {start: None}
    queue = [(0, next(serial), start)]
    while queue:
        cost, _, node = heapq.heappop(queue)
        if cost != best[node]: continue
        if node == goal:
            path = []
            while node is not None: path.append(node); node = parent[node]
            return cost, list(reversed(path))
        for neighbour, weight in graph[node]:
            candidate = cost + weight
            if candidate < best.get(neighbour, float("inf")):
                best[neighbour], parent[neighbour] = candidate, node
                heapq.heappush(queue, (candidate, next(serial), neighbour))
    return None
graph = {"A": [("B", 2)], "B": [], "Z": []}
assert route(graph, "A", "A") == (0, ["A"])
assert route(graph, "A", "Z") is None
cost, path = route(graph, "A", "B")
assert sum(dict(graph[u])[v] for u, v in zip(path, path[1:])) == cost
print("Route contracts verified")

Definition of done

  • □Reject negative weights and unknown endpoints.
  • □Return both route and cost for a reachable target.
  • □Return None for an unreachable known target.
  • □Return cost zero and a one-vertex route for equal endpoints.
  • □Test route validity as well as its cost.

06 Check your reasoning

QUICK SIGNAL CHECK

What should be verified in addition to total cost?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.