Directed Graphs and Walks
A directed graph (digraph) is a set of vertices and a set of directed edges, ordered pairs drawn as arrows . Web links, function calls, task dependencies, state machines and road maps with one-way streets are all digraphs. Formally a digraph is the same thing as a binary relation on .
Vocabulary
| Term | Meaning |
|---|---|
| out-degree / in-degree | number of edges leaving / entering a vertex |
| walk | a sequence of vertices with each an edge; its length is |
| path | a walk with no repeated vertex |
| closed walk | a walk that ends where it starts |
| cycle | a closed walk of positive length whose only repeated vertex is the start/end |
Lemma. If there is a walk from to , there is a path from to . Proof: take a shortest walk; if it repeated a vertex, cutting out the loop between the repeats would give a shorter walk.
Summing degrees counts each edge once at its tail and once at its head: .
Adjacency matrices count walks
Number the vertices . The adjacency matrix has if is an edge, else 0.
Theorem. is the number of walks of length from to .
Proof by induction on . For it is the definition. A walk of length from to is a walk of length from to some followed by an edge , so the count is .
import numpy as np
# vertices: 0 = home, 1 = shop, 2 = park, 3 = school
edges = [(0, 1), (0, 2), (1, 2), (2, 0), (2, 3), (3, 0)]
A = np.zeros((4, 4), dtype=np.int64)
for u, v in edges:
A[u, v] = 1
print("A =\n", A)
A3 = np.linalg.matrix_power(A, 3)
print("A^3 =\n", A3)
print("walks of length 3 from home to home:", A3[0, 0])A =
[[0 1 1 0]
[0 0 1 0]
[1 0 0 1]
[1 0 0 0]]
A^3 =
[[2 1 1 1]
[1 1 1 0]
[1 1 2 1]
[1 0 1 1]]
walks of length 3 from home to home: 2
So there are exactly 2 closed walks of length 3 that start at home. Listing all walks of length 3 from home and keeping those that return confirms it:
edges = {(0, 1), (0, 2), (1, 2), (2, 0), (2, 3), (3, 0)}
names = ["home", "shop", "park", "school"]
def walks(start, length):
if length == 0:
return [[start]]
return [[start] + w for (u, v) in sorted(edges) if u == start for w in walks(v, length - 1)]
for w in walks(0, 3):
if w[-1] == 0:
print(" -> ".join(names[x] for x in w))home -> shop -> park -> home
home -> park -> school -> home
Reachability and shortest paths
is reachable from when some walk leads from to . Breadth-first search (BFS) finds all reachable vertices and, at the same time, the length of a shortest path to each one. BFS explores vertices in order of distance, so it takes time, far faster than matrix powers on large sparse graphs.
from collections import deque
graph = {"a": ["b", "c"], "b": ["d"], "c": ["d", "e"], "d": ["f"], "e": ["f"], "f": [], "g": ["a"]}
def bfs(src):
dist = {src: 0}
q = deque([src])
while q:
u = q.popleft()
for v in graph[u]:
if v not in dist:
dist[v] = dist[u] + 1
q.append(v)
return dist
print("from a:", bfs("a"))
print("from d:", bfs("d"))from a: {'a': 0, 'b': 1, 'c': 1, 'd': 2, 'e': 2, 'f': 3}
from d: {'d': 0, 'f': 1}
Vertex g reaches everything but nothing reaches g: reachability is not symmetric in a digraph. Two vertices that reach each other are strongly connected. For weighted shortest paths see Dijkstra's algorithm.
In software
The web is a digraph of pages and links; PageRank analyses its walks (PageRank and Markov Chains). Garbage collectors compute reachability from root objects and free everything unreachable. Build systems, package managers and spreadsheet engines use dependency digraphs (next lesson). Social networks with "follow" (not "friend") are digraphs.
Exercises
Exercise 1: Degrees
A digraph has edges , , , , . Give each vertex's in- and out-degree and check the degree sum.
Answer
out: ; in: ; both sums are 5.
Solution
Count arrow tails for out-degree and heads for in-degree. Each of the 5 edges contributes 1 to each sum.
Exercise 2: Count walks with
For the graph of Exercise 1 (order ), how many walks of length 2 go from to ?
Answer
1 ().
Solution
. The middle vertex must be an out-neighbour of ( or ) with an edge to : only works.
Exercise 3: Walk to path
Explain why a shortest walk between two vertices never repeats a vertex.
Answer
Removing the loop between two visits of a repeated vertex gives a shorter walk.
Solution
If with , the walk is still a walk (the edge starts at ) and has length .
Exercise 4: Strongly connected? (code)
For the edges , find which pairs of vertices reach each other.
Answer
The strongly connected groups are and .
Solution
Compute the reachable set of every vertex and group vertices that reach each other.
edges = [(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 3)]
n = 5
reach = {u: {u} for u in range(n)}
changed = True
while changed: # transitive closure by repeated relaxation
changed = False
for u, v in edges:
for w in range(n):
if u in reach[w] and v not in reach[w]:
reach[w].add(v)
changed = True
groups = {frozenset(v for v in range(n) if v in reach[u] and u in reach[v]) for u in range(n)}
print(sorted(sorted(g) for g in groups))[[0, 1, 2], [3, 4]]
Test yourself
What does count for an adjacency matrix ?
- Edges from to
- Walks of length 3 from to
- Paths of any length
- The degree of
The sum of the out-degrees of all vertices equals…
- the number of vertices
- the number of edges
- twice the number of edges
- the sum of the in-degrees squared
Which algorithm finds shortest path lengths (in number of edges) from one vertex?
- Depth-first search
- Breadth-first search
- Euclid's algorithm
- Bubble sort