Sub topic 3
Directed Graphs: One-Way Relationships
This chapter assumes you can read Python dictionaries and sets, and that you know basic big-O notation. It covers what a directed graph is, how to store one, and the mistakes that come up most often.
What makes a graph directed
In a directed graph, each edge has a direction. An edge from A to B means you can go from A to B. It does not mean you can go from B to A. The vertex where the edge starts is the tail. The vertex where it ends is the head.
Many real relationships work this way:
- A user follows another user on a social network, but is not necessarily followed back.
- A web page links to another page.
- A task must finish before another task can start.
- A one-way street connects two intersections.
Directed edges are often written as ordered pairs, (A, B). The pair (B, A) is a different edge. A directed graph can hold both. Two such edges between the same vertices are called antiparallel edges, and they model a mutual relationship.
Storing a directed graph
The adjacency list from the previous chapter stores an undirected edge twice, once in each direction. A directed edge is stored once, under its tail only.
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
directed = {}
add_edge(directed, "A", "B", directed=True)
add_edge(directed, "B", "C", directed=True)
print(directed) # {'A': {'B': 1}, 'B': {'C': 1}, 'C': {}}The line graph.setdefault(v, {}) makes sure the head vertex exists as a key. Vertex C has no outgoing edges, but it must still appear in the dictionary. Without that line, later code such as graph["C"] would raise a KeyError.
Reading the structure
In this representation, the dictionary answers one question quickly: "Where can I go from here?" Looking up directed["A"] gives A's outgoing neighbors in time proportional to their number.
The reverse question is harder: "Who can reach me?" The graph stores no list of incoming edges, so you must scan every vertex.
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 costs O(1). in_degree costs O(V), because it checks each vertex's neighbor dictionary. If your program asks for incoming edges often, keep a second dictionary that stores the reversed graph.
Direction changes the answers
Reachability in a directed graph is not symmetric. In the graph A -> B -> C, you can get from A to C, but not from C to A. Some consequences:
- A path must follow edges in their stated direction.
- Two vertices can be connected in one direction only.
- A cycle needs a way back to the start. The loop
A -> B -> C -> Ais a cycle. The chainA -> B -> Cis not.
A traversal such as breadth-first search also follows direction. Starting from C in the chain above, it visits only C.
Common errors
- Forgetting the default. In the helper above,
directed=Falseis the default. If you leave outdirected=True, you silently build an undirected graph. - Missing sink vertices. A sink is a vertex with no outgoing edges. If it never becomes a key, lookups on it fail.
- Using the wrong degree. Total degree is not meaningful in a directed graph. Use in-degree and out-degree, which the next chapter covers in detail.
- Reading edges backward.
add_edge(g, "A", "B", directed=True)creates A to B only. Check which end is the tail before you test reachability.
Exercise
A directed graph is stored as {'X': {'Y': 1}, 'Y': {}, 'Z': {'X': 1, 'Y': 1}}. What are the in-degree and out-degree of Y, and which vertex is a sink?
Show answer
Y has in-degree 2, because X and Z both point to it, and out-degree 0. Y is the sink, since its neighbor dictionary is empty.