TExcelTAD
Home › Discrete Mathematics › Directed Graphs and Walks

Directed Graphs and Walks

A directed graph (digraph) G=(V,E)G = (V, E) is a set VV of vertices and a set EE of directed edges, ordered pairs (u,v)(u, v) drawn as arrows u→vu \to v. 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 VV.

Vocabulary

Term Meaning
out-degree / in-degree number of edges leaving / entering a vertex
walk a sequence of vertices v0,v1,…,vkv_0, v_1, \ldots, v_k with each vi→vi+1v_{i} \to v_{i+1} an edge; its length is kk
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 uu to vv, there is a path from uu to vv. Proof: take a shortest walk; if it repeated a vertex, cutting out the loop between the repeats would give a shorter walk. ■\blacksquare

Summing degrees counts each edge once at its tail and once at its head: ∑voutdeg(v)=∑vindeg(v)=∣E∣\sum_v \text{outdeg}(v) = \sum_v \text{indeg}(v) = \lvert E \rvert.

Adjacency matrices count walks

Number the vertices 1,…,n1, \ldots, n. The adjacency matrix AA has Aij=1A_{ij} = 1 if i→ji \to j is an edge, else 0.

Theorem. (Ak)ij(A^k)_{ij} is the number of walks of length kk from ii to jj.

Proof by induction on kk. For k=1k = 1 it is the definition. A walk of length k+1k + 1 from ii to jj is a walk of length kk from ii to some mm followed by an edge m→jm \to j, so the count is ∑m(Ak)imAmj=(Ak+1)ij\sum_m (A^k)_{im} A_{mj} = (A^{k+1})_{ij}. ■\blacksquare

python · try it yourself
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:

python · try it yourself
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

vv is reachable from uu when some walk leads from uu to vv. 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 O(∣V∣+∣E∣)O(\lvert V \rvert + \lvert E \rvert) time, far faster than matrix powers on large sparse graphs.

python · try it yourself
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 a→ba \to b, a→ca \to c, b→cb \to c, c→ac \to a, c→dc \to d. Give each vertex's in- and out-degree and check the degree sum.

Answer

out: a:2,b:1,c:2,d:0a{:}2, b{:}1, c{:}2, d{:}0; in: a:1,b:1,c:2,d:1a{:}1, b{:}1, c{:}2, d{:}1; 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 A2A^2

For the graph of Exercise 1 (order a,b,c,da, b, c, d), how many walks of length 2 go from aa to cc?

Answer

1 (a→b→ca \to b \to c).

Solution

(A2)ac=∑mAamAmc(A^2)_{ac} = \sum_m A_{am} A_{mc}. The middle vertex mm must be an out-neighbour of aa (bb or cc) with an edge to cc: only bb 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 vi=vjv_i = v_j with i<ji < j, the walk v0,…,vi,vj+1,…,vkv_0, \ldots, v_i, v_{j+1}, \ldots, v_k is still a walk (the edge vj→vj+1v_j \to v_{j+1} starts at viv_i) and has length k−(j−i)<kk - (j - i) < k.

Exercise 4: Strongly connected? (code)

For the edges 0→1,1→2,2→0,2→3,3→4,4→30 \to 1, 1 \to 2, 2 \to 0, 2 \to 3, 3 \to 4, 4 \to 3, find which pairs of vertices reach each other.

Answer

The strongly connected groups are {0,1,2}\{0, 1, 2\} and {3,4}\{3, 4\}.

Solution

Compute the reachable set of every vertex and group vertices that reach each other.

python · try it yourself
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 (A3)ij(A^3)_{ij} count for an adjacency matrix AA?

  1. Edges from ii to jj
  2. Walks of length 3 from ii to jj
  3. Paths of any length
  4. The degree of ii

The sum of the out-degrees of all vertices equals…

  1. the number of vertices
  2. the number of edges
  3. twice the number of edges
  4. the sum of the in-degrees squared

Which algorithm finds shortest path lengths (in number of edges) from one vertex?

  1. Depth-first search
  2. Breadth-first search
  3. Euclid's algorithm
  4. Bubble sort