Sub topic 3
Directed graphs: one-way relationships
This chapter assumes you know the basic graph vocabulary from the earlier chapters (vertices, edges, undirected graphs) and can read Python dictionaries, sets, and simple big-O notation. It covers what makes a graph directed, how to store one, and the mistakes that most often appear when code written for undirected graphs is reused.
What "directed" means
A directed graph (or digraph) is a set of vertices and a set of edges, where each edge is an ordered pair (u, v). The edge goes from u to v. The vertex u is the tail (or source) and v is the head (or target).
The order matters. The edge (A, B) does not imply that (B, A) exists. If both exist, they are two separate edges that happen to point in opposite directions.
Directed graphs model relationships that are not symmetric:
- Following an account on a social network. You can follow someone who does not follow you back.
- A hyperlink from one web page to another.
- A function that calls another function.
- A task that must finish before another task can start.
- A one-way street in a road network.
If a relationship is always mutual (a friendship that both people must accept, or a two-way road), an undirected graph is simpler. If either side can hold the relationship alone, use a directed graph.
In the diagram, A → C and C → A are two distinct edges. A → B has no matching B → A.
Storing a directed graph
In an adjacency list, an undirected edge is stored twice, once in each endpoint's neighbor collection. A directed edge is stored once, only in the tail's collection. The helper below uses a dictionary of dictionaries, where the inner value is the edge weight (1 by default).
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
undirected = {}
add_edge(undirected, "A", "B")
add_edge(undirected, "B", "C")
directed = {}
add_edge(directed, "A", "B", directed=True)
add_edge(directed, "B", "C", directed=True)
weighted = {}
add_edge(weighted, "A", "B", 4)
add_edge(weighted, "A", "C", 1)
add_edge(weighted, "C", "B", 2)
print(undirected) # {'A': {'B': 1}, 'B': {'A': 1, 'C': 1}, 'C': {'B': 1}}
print(directed) # {'A': {'B': 1}, 'B': {'C': 1}, 'C': {}}Two details in add_edge matter for directed graphs.
First, graph.setdefault(v, {}) makes sure the head vertex exists as a key even when it has no outgoing edges. In the output, 'C': {} is present. Without that line, graph["C"] would raise a KeyError in any traversal that reaches C.
Second, the directed flag is the only difference between the two models. The data structure is the same. What changes is whether the reverse entry is written.
In an adjacency matrix, a directed graph gives a matrix that is generally not symmetric. Entry [i][j] describes the edge from i to j, and [j][i] describes the opposite edge. An undirected graph always produces a symmetric matrix, so a quick symmetry check tells you which kind you have.
Common errors
Treating the neighbor set as "everyone connected to me"
In a directed adjacency list, graph[u] holds only the out-neighbors of u. It does not tell you who points at u. Code that asks "who is connected to u?" will silently miss every incoming edge.
Forgetting vertices that have no outgoing edges
A vertex that is only ever a head, like C above, must still be a key. If you build the dictionary with graph[u] = {v} alone, such vertices are missing and later lookups fail.
Reusing an undirected helper
Calling add_edge(g, "A", "B") without directed=True quietly creates two edges. The graph still looks plausible, but every question about reachability and direction now returns wrong answers.
Assuming reachability is symmetric
In an undirected graph, if u can reach v, then v can reach u. In a directed graph, that is false. Reachability from A to B says nothing about reachability from B to A.
Out-degree and in-degree
An undirected vertex has one degree. A directed vertex has two:
- The out-degree is the number of edges leaving the vertex.
- The in-degree is the number of edges entering it.
With an adjacency list, out-degree is a direct length lookup. In-degree needs a scan of the whole graph, because the list stores edges only at their tails.
def out_degree(graph, u):
return len(graph[u])
def in_degree(graph, u):
return sum(1 for v in graph if u in graph[v])
g = {}
add_edge(g, "A", "B", directed=True)
add_edge(g, "C", "B", directed=True)
print(out_degree(g, "A")) # 1
print(in_degree(g, "B")) # 2out_degree runs in O(1). in_degree checks every vertex's neighbor dictionary, so it runs in O(V), since each membership test on a dictionary is O(1) on average. If you need in-degrees for every vertex, do not call in_degree in a loop, which costs O(V²). Count them in one pass over the edges instead.
def all_in_degrees(graph):
counts = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
counts[v] += 1
return counts
print(all_in_degrees(g)) # {'A': 0, 'B': 2, 'C': 0}This runs in O(V + E). A vertex with in-degree 0 is a source of the graph, and a vertex with out-degree 0 is a sink. Sources and sinks become important later, when we look at directed acyclic graphs.
Summing over all vertices gives a useful identity. The total in-degree equals the total out-degree, and both equal the number of edges E. Each edge leaves exactly one vertex and enters exactly one vertex.
Paths and traversal follow the arrows
A path in a directed graph must follow edge directions. In the first diagram, A → B → C is a valid path. B → A is not a step, because there is no edge from B to A.
Breadth-first search carries over unchanged. It iterates over graph[u], which already holds only the out-neighbors, so it follows arrows automatically.
from collections import deque
def bfs(graph, start):
seen = {start}
order = []
queue = deque([start])
while queue:
u = queue.popleft()
order.append(u)
for v in graph[u]:
if v not in seen:
seen.add(v)
queue.append(v)
return order
print(bfs(undirected, "A")) # ['A', 'B', 'C']
print(bfs(directed, "A")) # ['A', 'B', 'C']
print(bfs(directed, "C")) # ['C']The last line shows the difference. Starting from C in the directed graph, nothing else is reachable, because C has no outgoing edges. The same start in the undirected graph would reach every vertex.
Cycles and the link to later topics
A directed cycle is a path that returns to its starting vertex. In the first diagram, A → C → A is a cycle of length 2. Undirected graphs need at least three vertices for a cycle in the usual sense, because walking an edge and then back along it does not count. In a directed graph, two opposite edges between the same pair of vertices already form a cycle.
A directed graph with no directed cycles is a directed acyclic graph (DAG). DAGs describe ordering constraints such as build dependencies and course prerequisites, and a later chapter covers them.
Connectivity also splits into two notions in directed graphs. A graph is strongly connected if every vertex can reach every other vertex by following arrows. It is weakly connected if the graph would be connected after ignoring the arrow directions. Our example is strongly connected only if every vertex can get back to every other one. In the first diagram, B can reach C and then A, so all three vertices can reach each other.
Summary of differences
| Aspect | Undirected | Directed |
|---|---|---|
| Edge | Unordered pair `{u, v}` | Ordered pair `(u, v)` |
| Adjacency list entries per edge | 2 | 1 |
| Adjacency matrix | Symmetric | Usually not symmetric |
| Degree | One value per vertex | In-degree and out-degree |
| Reachability | Symmetric | Not symmetric |
| Connectivity | Connected or not | Weak or strong |
Exercise
Using the add_edge helper with directed=True, build a graph with edges A→B, B→C, and C→A. Then give the out-degree and in-degree of every vertex, and say what happens when you run bfs from B.
Show answer
Every vertex has out-degree 1 and in-degree 1, because each vertex has one edge leaving and one entering. BFS from B visits ['B', 'C', 'A']: B leads to C, C leads to A, and A leads back to B, which is already seen. The three edges form a directed cycle, so every vertex is reachable from every other.
Exercise
A teammate writes graph.setdefault(u, set()).add(v) for each directed edge and no other line. The code then crashes with a KeyError during BFS on some inputs. What is the cause and the fix?
Show answer
Vertices that only appear as the head of an edge are never added as keys, so graph[v] fails when BFS reaches them. The fix is to also run graph.setdefault(v, set()) for every edge, as add_edge does.