Sub topic 13
Directed acyclic graphs and why they matter
This chapter assumes you can read the dictionary-of-dictionaries adjacency list from earlier chapters, and that you know what a directed edge, a path, and a cycle are. It also assumes you are comfortable with queues.
What a DAG is
A directed acyclic graph (DAG) is a directed graph with no cycles. You can never start at a vertex, follow edges in their direction, and return to where you began.
Two conditions must both hold:
- Every edge has a direction.
- No directed path leads from a vertex back to itself.
An undirected graph does not count, because its edges can be walked both ways. A single undirected edge already forms a loop in the directed sense.
Why they matter
A DAG models "must happen before" relationships. An edge u -> v means u has to come first.
- Build systems: a program must be compiled before it can be tested.
- Course prerequisites: you take Algebra before Calculus.
- Task schedulers and data pipelines: each step runs after the steps it depends on.
If such a graph had a cycle, the tasks could never be ordered. A task would have to wait for itself.
Topological order
A topological order lists every vertex so that each edge u -> v has u before v. A graph has one exactly when it is a DAG. A DAG often has several valid orders. In the diagram, test and package can come in either order.
Kahn's algorithm builds an order using in-degree, which you met earlier:
- Count the in-degree of every vertex.
- Queue every vertex with in-degree 0. These have no unmet dependencies.
- Remove a vertex from the queue and append it to the order.
- Lower the in-degree of each of its neighbors by 1. Queue any neighbor that reaches 0.
- Repeat until the queue is empty.
If the order is shorter than the vertex count, some vertices were never freed. That means a cycle blocked them.
from collections import deque
def add_edge(graph, u, v, weight=1, directed=False):
graph.setdefault(u, {})[v] = weight
graph.setdefault(v, {})
if not directed:
graph[v][u] = weight
def topological_order(graph):
in_deg = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
in_deg[v] += 1
ready = deque(u for u in graph if in_deg[u] == 0)
order = []
while ready:
u = ready.popleft()
order.append(u)
for v in graph[u]:
in_deg[v] -= 1
if in_deg[v] == 0:
ready.append(v)
if len(order) != len(graph):
raise ValueError("graph has a cycle")
return order
tasks = {}
add_edge(tasks, "compile", "test", directed=True)
add_edge(tasks, "compile", "package", directed=True)
add_edge(tasks, "test", "deploy", directed=True)
add_edge(tasks, "package", "deploy", directed=True)
print(topological_order(tasks)) # ['compile', 'test', 'package', 'deploy']
add_edge(tasks, "deploy", "compile", directed=True)
try:
topological_order(tasks)
except ValueError as error:
print(error) # graph has a cycleThe running time is O(V + E). Each vertex is queued once and each edge is examined once.
Common errors
- Passing an undirected graph. Every undirected edge is stored in both directions, so each one looks like a two-vertex cycle. No vertex on such an edge ever reaches in-degree 0, and the function raises the cycle error.
- Forgetting vertices that appear only as targets.
add_edgecreates an empty entry for every target. Without that entry,in_deg[v]fails with aKeyError. - Assuming the order is unique. Do not write tests that expect one specific order unless the DAG forces it.
Exercise
Exercise
A project has edges a -> b, b -> c, and a -> c. A teammate adds the edge c -> a. What does topological_order do on the new graph, and why?
Show answer
It raises ValueError("graph has a cycle"). The new edge creates the cycle a -> b -> c -> a. Each vertex of that cycle keeps an in-degree of at least 1 on its incoming cycle edge, so none is ever queued. The queue starts empty, the order stays shorter than the vertex count, and the check at the end fails.