Sub topic 13
Directed acyclic graphs and why they matter
This chapter assumes you know directed graphs, in-degree and out-degree, paths and cycles, the dictionary-of-dictionaries adjacency list used earlier in this tutorial, and queues. It covers what a directed acyclic graph (DAG) is, how to order its vertices with Kahn's algorithm, how that order detects cycles, and why a DAG gives you shortest paths even with negative weights.
What a DAG is
A directed acyclic graph is a directed graph with no cycle. Starting at any vertex and following edges in their direction, you can never return to where you began.
Two details of the definition cause most confusion:
- A self-loop (an edge from a vertex to itself) is a cycle of length 1, so a DAG has none.
- The word "directed" is required. An undirected edge
{A, B}can be walked from A to B and back to B to A, so any undirected edge would count as a cycle if you treated it as two directed edges. Acyclic undirected graphs have their own name, forests, and a connected one is a tree.
A DAG does not have to be connected, and it can have many paths between two vertices. A graph can have two routes from A to D and still be a DAG, as long as no route leads back.
Why DAGs matter
A DAG is the natural model for "X must happen before Y" relationships. Each edge u -> v means "u comes before v". A cycle would mean something must happen before itself, which is impossible to satisfy. Common examples:
- Build systems: a program cannot be linked before its files compile.
- Course prerequisites: you cannot require Calculus II for Calculus I.
- Spreadsheet formulas: a cell that depends on itself, directly or through other cells, is an error.
- Version history: a Git commit points to its parents, and history never loops back.
- Task schedulers and data pipelines: each step runs after the steps it depends on.
The diagram shows a small build graph. Every edge points from a step to a step that needs it.
Topological order
A topological order lists every vertex so that for each edge u -> v, u appears before v. For the build graph, parse, compile, link, docs, package works, and so does docs, parse, compile, link, package. A DAG usually has many valid orders. A directed graph has at least one if and only if it is a DAG, so finding an order doubles as a cycle test.
Kahn's algorithm
Kahn's algorithm builds the order by repeatedly taking a vertex with no remaining prerequisites:
- Compute the in-degree of every vertex.
- Put every vertex with in-degree 0 into a queue.
- Remove a vertex from the queue and append it to the output.
- For each of its outgoing edges, decrease the target's in-degree by 1. If that reaches 0, enqueue the target.
- Repeat until the queue is empty.
If the output contains every vertex, it is a valid topological order. If it is shorter, the unprocessed vertices all have a prerequisite that is also unprocessed, which means they lie on or behind a cycle.
from collections import deque
def topological_order(graph):
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] += 1
queue = deque(u for u in graph if indegree[u] == 0)
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in graph[u]:
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
if len(order) != len(graph):
raise ValueError("graph has a cycle")
return order
build = {
"compile": {"link": 1},
"parse": {"compile": 1},
"link": {"package": 1},
"package": {},
"docs": {"package": 1},
}
print(topological_order(build))
# ['parse', 'docs', 'compile', 'link', 'package']
looping = {"A": {"B": 1}, "B": {"C": 1}, "C": {"A": 1}}
try:
topological_order(looping)
except ValueError as error:
print(error) # graph has a cycleThe function assumes every vertex appears as a key in graph, including vertices with no outgoing edges. The add_edge helper from earlier in this tutorial guarantees that. If you build the dictionary by hand and leave out a sink vertex, indegree[v] += 1 raises a KeyError.
Cost
Computing in-degrees visits every edge once. The main loop dequeues each vertex once and examines each edge once. The total is O(V + E) time with O(V) extra space. This is far cheaper than calling the in_degree function from the degree chapter for each vertex, which scans the whole graph every time.
Depth-first alternative
You can also get a topological order from depth-first search. Run DFS from every unvisited vertex, append each vertex to a list when its recursive call finishes, then reverse the list. A cycle shows up as an edge pointing back to a vertex that is still on the current recursion stack. The two methods have the same O(V + E) cost. Kahn's algorithm is easier to write iteratively and avoids Python's recursion limit on deep graphs.
Several valid orders
Ties in the queue decide which valid order you get. In the build example, parse and docs both start with in-degree 0, and Kahn's algorithm took them in dictionary order. Treat the order as one of many valid answers, not the answer. Tests should check the defining property (every edge goes forward) instead of comparing against one fixed list:
def is_topological(graph, order):
position = {u: i for i, u in enumerate(order)}
return (
len(order) == len(graph)
and all(position[u] < position[v] for u in graph for v in graph[u])
)
print(is_topological(build, ["docs", "parse", "compile", "link", "package"])) # True
print(is_topological(build, ["package", "parse", "compile", "link", "docs"])) # FalseIf a program must produce the same order on every run, use a deterministic tie-breaker. One option is a heap that always releases the smallest available name.
Shortest paths in a DAG
Dijkstra's algorithm requires non-negative weights. A DAG offers a different route. Process vertices in topological order, and when you reach a vertex, its distance is already final. Every path into it must come through vertices earlier in the order. Relaxing each outgoing edge once is enough.
def dag_shortest(graph, source):
dist = {source: 0}
for u in topological_order(graph):
if u not in dist:
continue
for v, w in graph[u].items():
new_dist = dist[u] + w
if new_dist < dist.get(v, float("inf")):
dist[v] = new_dist
return dist
routes = {
"S": {"A": 2, "B": 6},
"A": {"B": -3, "C": 4},
"B": {"C": 1},
"C": {},
}
print(dag_shortest(routes, "S")) # {'S': 0, 'A': 2, 'B': -1, 'C': 0}This runs in O(V + E), faster than Dijkstra's O((V + E) log V) with a heap. It also handles the negative edge A -> B correctly. Negative weights are harmless because no cycle exists to loop around and reduce a distance forever. The same pattern with max in place of min finds the longest path in a DAG, which is how project schedulers compute the critical path. Longest path is hard on general graphs, so the DAG guarantee makes it tractable.
Common errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Treating an undirected graph as a DAG | Every edge is a two-step cycle, so no order exists | Model one-way dependencies with directed edges |
| Reversing edge direction | The order comes out backward | Decide that `u -> v` means "u before v" and keep to it |
| Omitting sink vertices from the dictionary | `KeyError` while counting in-degrees | Add every vertex as a key, even with an empty inner dictionary |
| Ignoring the length check | A cyclic graph returns a partial order that looks valid | Compare `len(order)` with `len(graph)` |
| Expecting a unique answer | Tests fail when tie-breaking changes | Test the property, or fix the tie-break rule |
| Recursive DFS on a deep chain | `RecursionError` | Use Kahn's algorithm or an explicit stack |
A topological order is unique only when the graph contains a path that visits every vertex. In that case there is exactly one choice at every step, and the queue never holds more than one vertex.
What to remember
- A DAG is a directed graph with no cycle, and it models "must come before" relationships.
- A directed graph has a topological order if and only if it is a DAG.
- Kahn's algorithm produces an order in O(V + E) and detects cycles when the output is shorter than the vertex count.
- On a DAG, relaxing edges in topological order gives shortest paths, even with negative weights, in O(V + E).
Exercise
Run Kahn's algorithm by hand on the graph {"a": {"b": 1, "c": 1}, "b": {"d": 1}, "c": {"d": 1}, "d": {}, "e": {"c": 1}}, with the queue seeded in dictionary order. What order does it return?
Show answer
In-degrees are a=0, b=1, c=2, d=2, e=0. The queue starts as [a, e]. Remove a: b drops to 0 and is enqueued, c drops to 1. Queue is [e, b]. Remove e: c drops to 0 and is enqueued. Queue is [b, c]. Remove b: d drops to 1. Remove c: d drops to 0 and is enqueued. Remove d. The order is ['a', 'e', 'b', 'c', 'd'].
Exercise
You add the edge d -> a to the graph in the previous exercise. What does topological_order do, and why?
Show answer
It raises ValueError("graph has a cycle"). Now a has in-degree 1, so the only vertex with in-degree 0 is e. The algorithm outputs e, then lowers c to 1 and stops with an empty queue. The output has 1 vertex out of 5. The remaining vertices a, b, c and d lie on the cycle a -> b -> d -> a or a -> c -> d -> a, so none of them ever reaches in-degree 0.