Sub topic 2
Directed Acyclic Graphs
This chapter assumes you can read Python, know what vertices and directed edges are, can store a graph as an adjacency list, and know how depth-first search works. Throughout the tutorial, an edge u -> v means "u must come before v."
The previous chapter modeled dependencies as directed graphs. Some dependency graphs can be scheduled and some cannot. The difference is whether the graph contains a directed cycle. This chapter defines the graphs with no directed cycles, explains what you can rely on when you have one, and covers the mistakes people often make when deciding whether a graph qualifies.
Paths, Cycles, and the Definition
A directed path is a sequence of vertices v0, v1, ..., vk where each consecutive pair is joined by an edge vi -> vi+1 that points forward. A directed cycle is a directed path with at least one edge that starts and ends at the same vertex. A self-loop u -> u is the shortest possible cycle.
A directed acyclic graph (DAG) is a directed graph that contains no directed cycle. Once you leave a vertex by following edges, you can never return to it.
Three details in this definition cause confusion:
- Only edge direction matters. If you ignore direction, a DAG can still contain a loop. That kind of loop is called an undirected cycle, and it is allowed.
- A DAG does not have to be connected. A graph made of three separate chains is still a DAG.
- Parallel edges, such as two copies of
a -> b, do not create a cycle. They are redundant, but the graph stays acyclic.
The diamond on the left forms a loop if you ignore arrows, but every path flows downward from a to d, so no path returns to where it started. On the right, reversing two of the edges creates a -> b -> d -> c -> a, which is a cycle.
Common Shapes
| Graph shape | Is it a DAG? | Reason |
|---|---|---|
| Rooted tree with edges pointing away from the root | Yes | Every path moves deeper and never comes back |
| Diamond (`a->b`, `a->c`, `b->d`, `c->d`) | Yes | It has an undirected cycle but no directed one |
| Single chain `a->b->c` | Yes | It has exactly one path through all the vertices |
| Graph with no edges | Yes | It has no paths at all, so it has no cycles |
| Any graph with a self-loop `u->u` | No | A cycle of length 1 |
| Two vertices with `a->b` and `b->a` | No | A cycle of length 2 |
| Mutual imports between two Python modules | No | Each module requires the other to load first |
Sources and Sinks
A source is a vertex with no incoming edges. A sink is a vertex with no outgoing edges. In a course plan, sources are the courses with no prerequisites and sinks are the courses that nothing else requires.
Every finite DAG with at least one vertex has at least one source and at least one sink. Here is the argument for sources. Start at any vertex and keep stepping backward along an incoming edge. In a DAG you can never revisit a vertex, because a revisit would close a cycle. The graph is finite, so the walk must stop, and it can only stop at a vertex with no incoming edge, which is a source. Walking forward along outgoing edges finds a sink in the same way.
A later chapter builds the existence theorem on this fact, and Kahn's algorithm depends on it directly. A cyclic graph can have no source at all. In the right-hand graph above, every vertex has an incoming edge.
The function below finds sources and sinks in an adjacency list. Pay attention to vertices that appear only as edge targets. A careless implementation misses them, which is a frequent bug.
def sources_and_sinks(graph):
"""graph maps each node to a list of nodes it points to (u -> v)."""
nodes = set(graph)
for targets in graph.values():
nodes.update(targets)
has_incoming = {v for targets in graph.values() for v in targets}
sources = sorted(nodes - has_incoming)
sinks = sorted(u for u in nodes if not graph.get(u))
return sources, sinks
courses = {
"intro": ["data_structures", "discrete_math"],
"discrete_math": ["algorithms"],
"data_structures": ["algorithms"],
# "algorithms" appears only as a target here
}
print(sources_and_sinks(courses))
# (['intro'], ['algorithms'])Because the function uses graph.get(u) and gathers every target into nodes, it still treats algorithms as a vertex, and as a sink, even though it has no key in the dictionary.
Reachability as a Partial Order
Say that v is reachable from u if there is a directed path from u to v. Count u as reachable from itself through a path of length zero. In a DAG, reachability has three properties:
- It is reflexive: every vertex reaches itself.
- It is transitive: if
ureachesvandvreachesw, thenureachesw. - It is antisymmetric: if
ureachesvandvreachesu, thenuandvare the same vertex.
A relation with these three properties is a partial order. Antisymmetry is the property that requires acyclicity. If two distinct vertices could each reach the other, the two paths together would form a cycle. So a DAG is a picture of a partial order. It tells you which items must come before which, and leaves some pairs unordered. For example, data_structures and discrete_math above are unordered relative to each other. A topological order, covered in the next chapter, extends this partial order into a single line.
How Many Edges a DAG Can Have
Line the vertices up in any order and allow only edges from earlier vertices to later ones. Every such graph is a DAG, and the most edges you can fit is one per pair: V(V-1)/2. Adding any further edge between distinct vertices would point backward and create a cycle. So a DAG can be dense, and algorithms on DAGs still need O(V + E) time, not O(V).
Keeping a Graph Acyclic as It Grows
Real systems often build dependency graphs one edge at a time, for example as a user adds tasks to a project. Adding u -> v creates a cycle exactly when u is already reachable from v, because the new edge would close that path into a loop. A reachability search before each insertion keeps the graph a DAG at all times.
def reachable(graph, start, target):
"""Return True if there is a directed path from start to target."""
stack = [start]
seen = {start}
while stack:
u = stack.pop()
if u == target:
return True
for v in graph.get(u, []):
if v not in seen:
seen.add(v)
stack.append(v)
return False
def add_edge_safely(graph, u, v):
"""Add u -> v only if the graph stays acyclic."""
if reachable(graph, v, u): # also catches u == v
raise ValueError(f"edge {u} -> {v} would create a cycle")
graph.setdefault(u, []).append(v)
graph.setdefault(v, [])
plan = {}
add_edge_safely(plan, "intro", "data_structures")
add_edge_safely(plan, "data_structures", "algorithms")
add_edge_safely(plan, "intro", "algorithms") # redundant but legal
try:
add_edge_safely(plan, "algorithms", "intro")
except ValueError as err:
print(err)
# edge algorithms -> intro would create a cycle
print(plan)
# {'intro': ['data_structures', 'algorithms'], 'data_structures': ['algorithms'], 'algorithms': []}Each check costs O(V + E), so building a graph of E edges this way costs O(E(V + E)) in the worst case. That is fine for interactive editing. For bulk loading, insert every edge first and check the whole graph once with one of the sorting algorithms in later chapters. Those algorithms detect cycles as a side effect.
Common Errors
- Mixing up edge direction. This tutorial uses
u -> vto mean "u before v." Some libraries, including Python'sgraphlib, instead map each node to its predecessors. Mixing the two conventions reverses every edge. The graph is still a DAG, but you get the order backward. - Calling an undirected loop a cycle. The diamond is a DAG. Check that every arrow in a suspected cycle points the same way around the loop.
- Forgetting self-loops. A task that lists itself as a dependency is a cycle. Data entry errors often produce this.
- Dropping vertices that appear only as targets. If your node set comes only from dictionary keys, sinks with no entry disappear.
- Assuming one source. A DAG can have many sources and many sinks, and it can be disconnected.
Exercise
A graph has edges a->b, b->c, a->c, c->d, and d->b. Is it a DAG? If not, name a directed cycle. Then identify every source.
Show answer
It is not a DAG. The path b->c->d->b is a directed cycle. Vertex a is the only source, since it is the only vertex with no incoming edges. This shows that a cyclic graph can still have a source, so finding a source does not prove that a graph is acyclic.
Exercise
Using addedgesafely, you start from an empty graph and add x->y, y->z, then z->x. Which call raises, and which reachability query decides it?
Show answer
The third call, addedgesafely(plan, "z", "x"), raises. It calls reachable(plan, "x", "z"), which finds the path x->y->z and returns True, so adding z->x would close the cycle x->y->z->x.
Exercise
What is the largest number of edges a DAG on 6 vertices can have, and why can no DAG on 6 vertices have more?
Show answer
6*5/2 = 15. Every DAG's vertices can be lined up so that all edges point forward, which allows at most one edge per unordered pair of distinct vertices. A 16th edge would have to repeat a pair in the opposite direction, or be a self-loop, and either creates a cycle.