Sub topic 2
Directed and undirected edges
This chapter assumes you know Python lists, dictionaries, and sets, and that you can read introductory Big-O notation. It covers how an edge's direction changes what the edge means and how you store it.
Two kinds of edge
An edge joins two vertices. It is undirected if the relationship runs both ways. It is directed if it runs one way only.
- Undirected: "A and B are friends" on a mutual-friendship network, or "road between A and B" on a two-way street map. The edge is an unordered pair, written {A, B}. {A, B} and {B, A} are the same edge.
- Directed: "A follows B" on a social feed, or "page A links to page B". The edge is an ordered pair, written (A, B). It leaves A, called the tail, and enters B, called the head. (A, B) and (B, A) are different edges, and a graph can contain one without the other.
A graph whose edges are all undirected is an undirected graph. A graph whose edges are all directed is a directed graph, or digraph.
What direction changes
Direction changes the questions you can ask.
In an undirected graph, if you can get from A to B, you can get from B to A. In a directed graph you can't assume that. In the right-hand graph above, A reaches D, but D reaches nothing.
Direction also changes the idea of degree. An undirected vertex has one degree: the number of edges touching it. A directed vertex has two:
- In-degree: the number of edges entering it.
- Out-degree: the number of edges leaving it.
In the directed graph above, A has in-degree 0 and out-degree 2. D has in-degree 2 and out-degree 0.
Storing direction
Edge direction decides how many entries you write per edge. The adjacency list below shows the rule.
from collections import defaultdict
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")]
undirected = defaultdict(list)
directed = defaultdict(list)
for u, v in edges:
undirected[u].append(v)
undirected[v].append(u) # undirected: record both directions
directed[u].append(v) # directed: record only tail -> head
print(undirected["D"]) # ['B', 'C']
print(directed["D"]) # []
print(directed["A"]) # ['B', 'C']For an undirected edge, the code writes two entries, one in each endpoint's list. For a directed edge, it writes one entry, in the tail's list.
The adjacency matrix follows the same rule. An undirected graph gives a symmetric matrix, where matrix[i][j] == matrix[j][i] for every pair. A directed graph can give an asymmetric one.
nodes = ["A", "B", "C", "D"]
index = {name: i for i, name in enumerate(nodes)}
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")]
matrix = [[0] * len(nodes) for _ in nodes]
for u, v in edges:
matrix[index[u]][index[v]] = 1 # directed: one cell only
print(matrix[index["A"]][index["B"]]) # 1
print(matrix[index["B"]][index["A"]]) # 0An edge list needs no extra work for direction. It stores pairs. You only have to decide whether ("A", "B") means "from A to B" or "A and B are joined". Choose one reading and keep it everywhere.
Common errors
- Forgetting the reverse entry. If you build an undirected graph but append only
graph[u].append(v), traversals fromvwill missu. The graph silently behaves as a directed one. - Adding the reverse entry to a directed graph. This turns every edge into a two-way edge and changes the answers.
- Counting edges twice. An undirected graph stored as an adjacency list holds
2 * Eentries. Divide by 2 when counting its edges. - Mixing conventions. Passing an undirected edge list into code that expects directed edges gives wrong reachability results.
Exercise
A directed graph has edges ("X", "Y"), ("Y", "Z"), and ("Z", "Y"). What are the in-degree and out-degree of Y, and can you reach X from Z?
Show answer
Y has in-degree 2 (from X and from Z) and out-degree 1 (to Z). You cannot reach X from Z, because no edge enters X.
Exercise
You store an undirected graph with 5 edges as an adjacency list. How many neighbor entries does the structure hold in total, and why?
Show answer
10. Each undirected edge is recorded once in each endpoint's list, so the total is 2 * 5.