---
title: "Graphs and Traversals"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 24
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 24 — Graphs and Traversals

Brenmoor has thirty places, fifty-three roads and a single one-way street, from the Town Square to the Library. Can every place still reach every other? The town council would like to go further and make every road one-way, to widen the pavements: is that possible without cutting anyone off? Both questions are about reachability in a [graph](#def-b1-graph-traversals-graph), and both are answered by a program that walks the [graph](#def-b1-graph-traversals-graph) in a well-chosen order. This chapter builds the two walks, depth first and breadth first, and what they compute: [distances](#def-b1-graph-traversals-distance), components, orders, and the roads that cannot be spared.

**You already know.**

The second book drew [graphs](#def-b1-graph-traversals-graph), computed [distances](#def-b1-graph-traversals-distance) in a [graph](#def-b1-graph-traversals-graph) by [breadth-first search](#def-b1-graph-traversals-bfs) and routes by Dijkstra’s algorithm. The mathematics book represents a [graph](#def-b1-graph-traversals-graph) by its adjacency matrix. Stacks and queues were built in [Chapter 15](https://one-course.com/books/computer-science/3/en/chapter/15-linked-structures-lists-stacks-and-queues#ch-b1-linked-structures).

## 24.1 Definitions

**Definition 24.1 (Graph, vertex, edge, arc, loop).**

A *graph* $G = (V, E)$ is a finite set $V$ of *vertices* and a set $E$ of *edges*. In an *undirected graph* an edge is a set $\{u, v\}$ of two vertices, its *ends*, written $uv$. In a *directed graph* an edge is a pair $(u, v)$, an *arc* from $u$ to $v$, written $u \to v$. An edge whose two ends are equal is a *loop*; unless stated otherwise, graphs here have no loops and $n = |V|$, $m = |E|$.

**Definition 24.2 (Degree).**

The *degree* $\deg(v)$ of a [vertex](#def-b1-graph-traversals-graph) of an undirected [graph](#def-b1-graph-traversals-graph) is the number of [edges](#def-b1-graph-traversals-graph) at $v$; its *neighbours* are the other ends of these [edges](#def-b1-graph-traversals-graph). In a [directed graph](#def-b1-graph-traversals-graph), the *out-degree* of $v$ counts the [arcs](#def-b1-graph-traversals-graph) leaving $v$, its *in-degree* those arriving at $v$.

**Proposition 24.3 (Handshake lemma).**

In an undirected [graph](#def-b1-graph-traversals-graph), $\sum_v \deg(v) = 2m$; so the number of [vertices](#def-b1-graph-traversals-graph) of odd [degree](#def-b1-graph-traversals-degree) is even. In a [directed graph](#def-b1-graph-traversals-graph), the [out-degrees](#def-b1-graph-traversals-degree) and the [in-degrees](#def-b1-graph-traversals-degree) both sum to $m$.

**Proof.** Each edge $uv$ is counted twice in the sum, once in $\deg(u)$ and once in $\deg(v)$; each [arc](#def-b1-graph-traversals-graph) once among the [out-degrees](#def-b1-graph-traversals-degree), at its tail, and once among the [in-degrees](#def-b1-graph-traversals-degree), at its head. The sum of the even [degrees](#def-b1-graph-traversals-degree) is even, so the odd [degrees](#def-b1-graph-traversals-degree) have an even sum, which needs an even number of them. ∎

**Definition 24.4 (Path, simple path, cycle).**

A *path* of length $k$ from $u$ to $v$ is a sequence of [vertices](#def-b1-graph-traversals-graph) $u = v_0, v_1, \dots, v_k = v$ where each $v_{i-1} v_i$ is an edge (an [arc](#def-b1-graph-traversals-graph) $v_{i-1} \to v_i$ in a [directed graph](#def-b1-graph-traversals-graph)). It is *simple* if its [vertices](#def-b1-graph-traversals-graph) are distinct. A *cycle* is a path of length at least 1 from a [vertex](#def-b1-graph-traversals-graph) to itself whose other [vertices](#def-b1-graph-traversals-graph) are distinct and distinct from it; in an undirected [graph](#def-b1-graph-traversals-graph) its length must be at least 3 and it uses no edge twice. $v$ is *reachable* from $u$ if there is a path from $u$ to $v$.

**Definition 24.5 (Distance).**

The *distance* $\delta(u, v)$ is the smallest length of a [path](#def-b1-graph-traversals-path) from $u$ to $v$, counted in [edges](#def-b1-graph-traversals-graph), and $\infty$ if $v$ is not reachable from $u$.

**Definition 24.6 (Connected, strongly connected).**

An undirected [graph](#def-b1-graph-traversals-graph) is *connected* if every [vertex](#def-b1-graph-traversals-graph) is reachable from every other. Being reachable from one another is an equivalence relation on the [vertices](#def-b1-graph-traversals-graph); its classes are the *connected components*. In a [directed graph](#def-b1-graph-traversals-graph), $u$ and $v$ are *strongly connected* when each is reachable from the other; the classes of this equivalence are the *strongly connected components*, and the [graph](#def-b1-graph-traversals-graph) is *strongly connected* if there is only one.

**Definition 24.7 (Directed acyclic graph).**

A *directed acyclic graph*, or DAG, is a [directed graph](#def-b1-graph-traversals-graph) without a [cycle](#def-b1-graph-traversals-path).

**Definition 24.8 (Free tree, forest).**

A *free tree* is a [connected](#def-b1-graph-traversals-connected) undirected [graph](#def-b1-graph-traversals-graph) without a [cycle](#def-b1-graph-traversals-path); a *forest* is an undirected [graph](#def-b1-graph-traversals-graph) without a [cycle](#def-b1-graph-traversals-path), whose components are free trees. Choosing a [vertex](#def-b1-graph-traversals-graph) as the root turns a free tree into a [rooted tree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) ([Definition 11.2](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree)).

**Proposition 24.9 (Free trees).**

For an undirected [graph](#def-b1-graph-traversals-graph) $G$ with $n \geq 1$ [vertices](#def-b1-graph-traversals-graph), the following are equivalent: (i) $G$ is a [free tree](#def-b1-graph-traversals-free-tree); (ii) any two [vertices](#def-b1-graph-traversals-graph) are joined by exactly one [simple path](#def-b1-graph-traversals-path); (iii) $G$ is [connected](#def-b1-graph-traversals-connected) and has $n - 1$ [edges](#def-b1-graph-traversals-graph).

**Proof.** (i)$\Rightarrow$(ii): a [simple path](#def-b1-graph-traversals-path) exists, since $G$ is [connected](#def-b1-graph-traversals-connected) and a shortest [path](#def-b1-graph-traversals-path) is [simple](#def-b1-graph-traversals-path). If two different [simple paths](#def-b1-graph-traversals-path) join $u$ and $v$, follow them from $u$ to the first [vertex](#def-b1-graph-traversals-graph) where they part, $x$, and on the first one to the first [vertex](#def-b1-graph-traversals-graph) after $x$ that the second one also visits, $y$; the two pieces from $x$ to $y$ share only their ends and make a [cycle](#def-b1-graph-traversals-path). (ii)$\Rightarrow$(i): $G$ is [connected](#def-b1-graph-traversals-connected), and a [cycle](#def-b1-graph-traversals-path) through $u v$ would give two [simple paths](#def-b1-graph-traversals-path) from $u$ to $v$, the edge and the rest of the [cycle](#def-b1-graph-traversals-path). (i)$\Leftrightarrow$(iii) is [Exercise 24.9](#exo-b1-graph-traversals-9). ∎

**Definition 24.10 (Bipartite graph).**

An undirected [graph](#def-b1-graph-traversals-graph) is *bipartite* if its [vertices](#def-b1-graph-traversals-graph) can be coloured with two colours so that every edge joins two [vertices](#def-b1-graph-traversals-graph) of different colours.

**Definition 24.11 (Weighted graph, labelled graph).**

A *weighted graph* has a number, its weight, on each edge; a *labelled graph* has a value of any kind on each edge or [vertex](#def-b1-graph-traversals-graph): a road’s length, a street’s name.

## 24.2 Representations and their costs

The mathematics book stores a [graph](#def-b1-graph-traversals-graph) in its adjacency matrix: an $n \times n$ table whose entry $(u, v)$ is 1 when $u v$ is an edge. Programs more often keep, for each [vertex](#def-b1-graph-traversals-graph), the list of its neighbours.

**Definition 24.12 (Adjacency list, edge list).**

The *adjacency lists* of a [graph](#def-b1-graph-traversals-graph) give, for each [vertex](#def-b1-graph-traversals-graph), the list of its neighbours (in a [directed graph](#def-b1-graph-traversals-graph), the heads of its [arcs](#def-b1-graph-traversals-graph)). Its *edge list* is the list of its [edges](#def-b1-graph-traversals-graph), as pairs of [vertices](#def-b1-graph-traversals-graph).

```python
@dataclass
class Graph:
    directed: bool
    adj: dict = field(default_factory=dict)  # vertex -> list of neighbours

    def add_vertex(self, v):
        self.adj.setdefault(v, [])

    def add_edge(self, u, v):
        self.add_vertex(u)
        self.add_vertex(v)
        self.adj[u].append(v)
        if not self.directed:
            self.adj[v].append(u)  # an undirected edge is stored at both ends

    def vertices(self):
        return list(self.adj)

    def edges(self):
        """Each edge once: (u, v) with u before v in an undirected graph."""
        order = {v: i for i, v in enumerate(self.adj)}
        return [(u, v) for u in self.adj for v in self.adj[u]
                if self.directed or order[u] < order[v] or u == v]
def roads():
    """Places joined by roads; a one-way road is an arc, any other road two arcs."""
    g = Graph(directed=True)
    for p in rows("places"):
        g.add_vertex(int(p["place_id"]))
    for r in rows("roads"):
        a, b = int(r["from_place"]), int(r["to_place"])
        g.add_edge(a, b)
        if r["one_way"] == "0":
            g.add_edge(b, a)
    return g
```

***Listing 24.1.** A [graph](#def-b1-graph-traversals-graph) as [adjacency lists](#def-b1-graph-traversals-lists), and the town’s roads loaded code/bachelor-1/24-graph-traversals/listings/graph.py*

```
$ python graph.py
roads: 30 vertices, 105 edges (arcs), out-degrees 2 to 5, sum 105
friendships: 40 vertices, 50 edges (undirected), degrees 0 to 5, sum 100
```

***Output 24.1.** The two [graphs](#def-b1-graph-traversals-graph) of the town: each two-way road is two [arcs](#def-b1-graph-traversals-graph), so the roads give $2 \times 53 - 1 = 105$ [arcs](#def-b1-graph-traversals-graph).*

The [degrees](#def-b1-graph-traversals-degree) of the friendship [graph](#def-b1-graph-traversals-graph) sum to 100, twice its 50 [edges](#def-b1-graph-traversals-graph), as the handshake lemma says; the [out-degrees](#def-b1-graph-traversals-degree) of the road [graph](#def-b1-graph-traversals-graph) sum to its number of [arcs](#def-b1-graph-traversals-graph).

|  | adjacency matrix | [adjacency lists](#def-b1-graph-traversals-lists) | [edge list](#def-b1-graph-traversals-lists) |
| --- | --- | --- | --- |
| space | $\Theta(n^2)$ | $\Theta(n + m)$ | $\Theta(m)$ |
| is $u v$ an edge? | $O(1)$ | $O(\deg u)$ | $O(m)$ |
| the neighbours of $u$ | $\Theta(n)$ | $\Theta(\deg u)$ | $\Theta(m)$ |
| add an edge | $O(1)$ | $O(1)$ | $O(1)$ |

```
$ python representations.py
graph          n    m matrix cells list entries edge list
roads         30  105          900          135       210
friendships   40   50         1600          140       100
```

***Output 24.2.** Numbers each representation stores: the lists hold one entry per [vertex](#def-b1-graph-traversals-graph) and one per [arc](#def-b1-graph-traversals-graph), twice as many per edge in an undirected [graph](#def-b1-graph-traversals-graph).*

A [graph](#def-b1-graph-traversals-graph) is *sparse* when $m$ is much smaller than $n^2$, as for roads and friendships, whose [degrees](#def-b1-graph-traversals-degree) stay small however large the town; [adjacency lists](#def-b1-graph-traversals-lists) are then the right choice, and every algorithm of this chapter runs in time $O(n + m)$ on them. To store a [graph](#def-b1-graph-traversals-graph) in a file, an [edge list](#def-b1-graph-traversals-lists) is the simplest: one line per edge.

```python
def write(g, path):
    """First line: 'directed' or 'undirected', and the vertices; one edge a line."""
    lines = [("directed" if g.directed else "undirected") + " "
             + " ".join(map(str, g.vertices()))]
    lines += [f"{u} {v}" for u, v in g.edges()]
    Path(path).write_text("\n".join(lines) + "\n")


def read(path):
    first, *rest = Path(path).read_text().splitlines()
    kind, *names = first.split()
    g = Graph(directed=kind == "directed")
    for v in names:
        g.add_vertex(int(v))
    for line in rest:
        u, v = map(int, line.split())
        g.add_edge(u, v)
    return g
```

***Listing 24.2.** A [graph](#def-b1-graph-traversals-graph) written as an [edge list](#def-b1-graph-traversals-lists) and read back code/bachelor-1/24-graph-traversals/listings/edge_file.py*

```
$ python edge_file.py
106 lines; first two edges: '1 3', '1 23'
read back: same vertices and arcs: True
```

***Output 24.3.** The road [graph](#def-b1-graph-traversals-graph) survives the round trip through a file.*

The first line also lists the [vertices](#def-b1-graph-traversals-graph), so that a [vertex](#def-b1-graph-traversals-graph) without [edges](#def-b1-graph-traversals-graph), such as person 40 of the friendship [graph](#def-b1-graph-traversals-graph), is not lost.

## 24.3 Depth-first search

**Definition 24.13 (Depth-first search, discovery and finishing times).**

A *depth-first search* visits a [vertex](#def-b1-graph-traversals-graph) $u$ by marking it, then visiting in turn each unmarked neighbour of $u$; on the whole [graph](#def-b1-graph-traversals-graph), it visits each [vertex](#def-b1-graph-traversals-graph) not yet marked. A clock ticks at each start and each end of a visit: $u$’s *discovery time* $d(u)$ is the tick when its visit starts, its *finishing time* $f(u)$ the tick when it ends. Between the two, $u$ is *open*. If the visit of $u$ calls the visit of $v$, $u$ is the *parent* of $v$; the parent links form the *DFS [forest](#def-b1-graph-traversals-free-tree)*.

**Definition 24.14 (Classes of arcs).**

In a [depth-first search](#def-b1-graph-traversals-dfs) of a [directed graph](#def-b1-graph-traversals-graph), an [arc](#def-b1-graph-traversals-graph) $u \to v$ is a *tree edge* if $u$ is the parent of $v$; a *back edge* if $v$ is an ancestor of $u$ in the [forest](#def-b1-graph-traversals-free-tree), or $u$ itself; a *forward edge* if $v$ is a descendant of $u$ but not its child; a *cross edge* otherwise.

```python
def dfs(g):
    """(discovery, finish, parent, classes): times run 1, 2, ...; classes maps each arc
    to 'tree', 'back', 'forward' or 'cross'."""
    disc, fin, parent, classes = {}, {}, {}, {}
    clock = 0

    def visit(u):
        nonlocal clock
        clock += 1
        disc[u] = clock  # u is now open: discovered, not finished
        for v in g.adj[u]:
            if v not in disc:
                classes[u, v] = "tree"
                parent[v] = u
                visit(v)
            elif v not in fin:
                classes[u, v] = "back"  # v is open: an ancestor of u
            elif disc[u] < disc[v]:
                classes[u, v] = "forward"  # v finished, a descendant of u
            else:
                classes[u, v] = "cross"
        clock += 1
        fin[u] = clock

    for s in g.vertices():
        if s not in disc:
            parent[s] = None
            visit(s)
    return disc, fin, parent, classes
```

***Listing 24.3.** [Depth-first search](#def-b1-graph-traversals-dfs): times, and the class of each [arc](#def-b1-graph-traversals-graph) code/bachelor-1/24-graph-traversals/listings/dfs.py*

When the [arc](#def-b1-graph-traversals-graph) $u \to v$ is examined, $v$ is unmarked (a [tree edge](#def-b1-graph-traversals-edge-classes)), open (on the chain of visits in progress, so an ancestor: a [back edge](#def-b1-graph-traversals-edge-classes)), or finished, and then a descendant of $u$ exactly when it was discovered after $u$.

```
$ python dfs.py
a 1/8  b 2/5  c 6/7  d 3/4  e 9/16  f 10/15  g 11/14  h 12/13
tree     ab bd ac ef fg gh
back     da ge
forward  ad
cross    cb ec
iterative, from a: a b d c
```

***Output 24.4.** A small [directed graph](#def-b1-graph-traversals-graph): times, classes, and the order of the iterative search.*

![The search of , started at a, then at e; each vertex carries d|f. The tree edges form two trees, rooted at a and e.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-graph-traversals/fig-a2f8b6ba8d32.svg)

*The search of [Output 24.4](#out-b1-graph-traversals-dfs), started at `a`, then at `e`; each [vertex](#def-b1-graph-traversals-graph) carries $d|f$. The [tree edges](#def-b1-graph-traversals-edge-classes) form two trees, rooted at `a` and `e`.*

**Theorem 24.15 (Parenthesis theorem).**

For any two [vertices](#def-b1-graph-traversals-graph) $u$ and $v$ of a [depth-first search](#def-b1-graph-traversals-dfs), the intervals $[d(u), f(u)]$ and $[d(v), f(v)]$ are disjoint or one contains the other; and $[d(v), f(v)] \subset [d(u), f(u)]$ exactly when $v$ is a descendant of $u$, $v \neq
u$.

**Proof.** Say $d(u) < d(v)$. If $v$ is discovered while $u$ is open, $v$’s visit is called, directly or not, from $u$’s, so $v$ is a descendant of $u$; and a call returns before its caller does, so $f(v) < f(u)$: nested. Otherwise $u$ finished before $d(v)$: disjoint. Conversely, a descendant of $u$ is discovered during $u$’s visit, so its interval is nested in $u$’s. ∎

Writing an opening bracket at each discovery and a closing one at each finish gives a well-bracketed word, hence the name. A second fact explains what the search finds: when $v$ is discovered, every [vertex](#def-b1-graph-traversals-graph) reachable from $v$ by a [path](#def-b1-graph-traversals-path) of unmarked [vertices](#def-b1-graph-traversals-graph) becomes a descendant of $v$ (the *[white-path](#def-b1-graph-traversals-path)* property; take the first [vertex](#def-b1-graph-traversals-graph) of such a [path](#def-b1-graph-traversals-path) that would not be a descendant: its predecessor on the [path](#def-b1-graph-traversals-path) is one, and examines it before finishing).

**Proposition 24.16 (Cycles and back edges).**

A [directed graph](#def-b1-graph-traversals-graph) is acyclic if and only if a [depth-first search](#def-b1-graph-traversals-dfs) finds no [back edge](#def-b1-graph-traversals-edge-classes).

**Proof.** A [back edge](#def-b1-graph-traversals-edge-classes) $u \to v$, with $v$ an ancestor of $u$, closes a [cycle](#def-b1-graph-traversals-path) with the tree [path](#def-b1-graph-traversals-path) from $v$ to $u$. Conversely, let $C$ be a [cycle](#def-b1-graph-traversals-path) and $v$ its first [vertex](#def-b1-graph-traversals-graph) to be discovered, and $u \to v$ the [arc](#def-b1-graph-traversals-graph) of $C$ that enters $v$. At $d(v)$ the rest of $C$ is unmarked, so $u$ becomes a descendant of $v$ by the [white-path](#def-b1-graph-traversals-path) property, and $u \to v$ is a [back edge](#def-b1-graph-traversals-edge-classes). ∎

The recursive search can run out of Python’s [call stack](https://one-course.com/books/computer-science/3/en/chapter/3-functions-and-the-call-stack#def-b1-c-functions-and-stack-call-stack) on a long [path](#def-b1-graph-traversals-path). An explicit stack does the same work in a loop; pushing all the neighbours at once, it discovers the [vertices](#def-b1-graph-traversals-graph) in the same order, but it no longer knows when a [vertex](#def-b1-graph-traversals-graph) finishes. For [finishing times](#def-b1-graph-traversals-dfs), the stack holds each open [vertex](#def-b1-graph-traversals-graph) with the [iterator](https://one-course.com/books/computer-science/3/en/chapter/15-linked-structures-lists-stacks-and-queues#def-b1-linked-structures-iterator) over its remaining [arcs](#def-b1-graph-traversals-graph) ([Listing 24.9](#lst-b1-graph-traversals-kosaraju)).

```python
def dfs_iterative(g, s):
    """The vertices reachable from s in the order a stack discovers them."""
    seen, order, stack = set(), [], [s]
    while stack:
        u = stack.pop()
        if u in seen:
            continue
        seen.add(u)
        order.append(u)
        stack.extend(reversed(g.adj[u]))  # so that neighbours come off in list order
    return order
```

***Listing 24.4.** The order of discovery, with a stack code/bachelor-1/24-graph-traversals/listings/dfs.py*

## 24.4 Breadth-first search

**Definition 24.17 (Breadth-first search, BFS tree).**

A *breadth-first search* from $s$ keeps a queue of discovered [vertices](#def-b1-graph-traversals-graph), initially $s$; it removes the [vertex](#def-b1-graph-traversals-graph) $u$ at the head and discovers each undiscovered neighbour $v$ of $u$, setting $\texttt{dist}[v] =
\texttt{dist}[u] + 1$ and the parent of $v$ to $u$, and adds it at the tail. The parent links form the *BFS tree*, rooted at $s$.

```python
def bfs(g, s):
    """(dist, parent): dist[v] is the number of edges of a shortest path from s to v."""
    dist, parent = {s: 0}, {s: None}
    queue = deque([s])
    while queue:
        u = queue.popleft()  # vertices leave in the order of their distance
        for v in g.adj[u]:
            if v not in dist:
                dist[v] = dist[u] + 1
                parent[v] = u
                queue.append(v)
    return dist, parent
```

***Listing 24.5.** [Breadth-first search](#def-b1-graph-traversals-bfs) with a queue code/bachelor-1/24-graph-traversals/listings/bfs.py*

**Theorem 24.18 (Breadth-first search computes distances).**

At the end of a [breadth-first search](#def-b1-graph-traversals-bfs) from $s$, the discovered [vertices](#def-b1-graph-traversals-graph) are those reachable from $s$, $\texttt{dist}[v] =
\delta(s, v)$ for each, and the [path](#def-b1-graph-traversals-path) of parents from $v$ up to $s$, read backwards, is a shortest [path](#def-b1-graph-traversals-path).

**Proof.** Invariant: the values of `dist` in the queue, from head to tail, are non-decreasing and differ by at most 1. It holds for $[s]$; removing the head $u$, of value $k$, and appending [vertices](#def-b1-graph-traversals-graph) of value $k + 1$ keeps it, since the other values were between $k$ and $k + 1$. So [vertices](#def-b1-graph-traversals-graph) leave the queue by non-decreasing `dist`. Each $\texttt{dist}[v]$ is the length of the parent [path](#def-b1-graph-traversals-path), so $\texttt{dist}[v] \geq \delta(s, v)$. Suppose some $v$ has $\texttt{dist}[v] >
\delta(s, v) = k$, with $k$ smallest; $k \geq 1$, and let $u$ be the [vertex](#def-b1-graph-traversals-graph) before $v$ on a shortest [path](#def-b1-graph-traversals-path), so $\texttt{dist}[u] = \delta(s, u) = k - 1$. When $u$ left the queue, $v$ was discovered then, with value $k$, or before, from a [vertex](#def-b1-graph-traversals-graph) that left the queue no later than $u$, with value at most $k$: a contradiction. Reachable [vertices](#def-b1-graph-traversals-graph) are discovered by the same argument, with $\infty$ in place of a value. ∎

```
$ python bfs.py
distance 0:  1 places [1]
distance 1:  4 places [3, 23, 24, 26]
distance 2:  4 places [7, 10, 16, 21]
distance 3:  6 places [2, 4, 9, 15, 18, 28]
distance 4:  7 places [11, 14, 17, 19, 20, 27, 29]
distance 5:  5 places [5, 6, 13, 22, 25]
distance 6:  3 places [8, 12, 30]
farthest: Hospital, by
  Town Square -> North Bridge -> River Park -> Town Hall ->
  Fire Station -> Clinic -> Hospital
```

***Output 24.5.** The places by number of roads from the Town Square, and a farthest one.*

![Brenmoor’s roads, drawn from the coordinates of the places by figures/town_graphs.py; the one-way road is the arrow. Each place carries its distance in roads from the Town Square: the layers of .](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-graph-traversals/fig-4e99afbda749.svg)

*Brenmoor’s roads, drawn from the coordinates of the places by `figures/town_graphs.py`; the one-way road is the arrow. Each place carries its [distance](#def-b1-graph-traversals-distance) in roads from the Town Square: the layers of [Output 24.5](#out-b1-graph-traversals-bfs).*

[Breadth-first search](#def-b1-graph-traversals-bfs) counts roads, not metres: the route it finds to the Hospital has the fewest roads, not the fewest kilometres. Lengths are the business of [Chapter 25](https://one-course.com/books/computer-science/3/en/chapter/25-shortest-paths#ch-b1-shortest-paths).

The same search two-colours a [graph](#def-b1-graph-traversals-graph): colour $s$ with 0, and each newly discovered [vertex](#def-b1-graph-traversals-graph) with the colour its parent does not have. If an edge joins two [vertices](#def-b1-graph-traversals-graph) of the same colour, the [graph](#def-b1-graph-traversals-graph) is not [bipartite](#def-b1-graph-traversals-bipartite), and the edge with the two tree [paths](#def-b1-graph-traversals-path) up to the common ancestor of its ends is an odd [cycle](#def-b1-graph-traversals-path): the two [paths](#def-b1-graph-traversals-path) have lengths of the same parity, since the colours of their ends agree.

```python
def two_colour(g):
    """(colour, None) if g is bipartite, else (None, an odd cycle as a vertex list)."""
    colour, parent = {}, {}
    for s in g.vertices():  # every component
        if s in colour:
            continue
        colour[s], parent[s] = 0, None
        queue = deque([s])
        while queue:
            u = queue.popleft()
            for v in g.adj[u]:
                if v not in colour:
                    colour[v], parent[v] = 1 - colour[u], u
                    queue.append(v)
                elif colour[v] == colour[u]:  # an edge inside one colour
                    return None, odd_cycle(parent, u, v)
    return colour, None


def odd_cycle(parent, u, v):
    """The two tree paths from u and v up to their common ancestor, plus the edge uv."""
    up_u, up_v = [u], [v]
    while up_u[-1] is not None:
        up_u.append(parent[up_u[-1]])
    while up_v[-1] is not None:
        up_v.append(parent[up_v[-1]])
    ancestors = set(up_v)
    top = next(x for x in up_u if x in ancestors)
    return up_u[:up_u.index(top) + 1] + up_v[:up_v.index(top)][::-1]
```

***Listing 24.6.** Two colours, or an odd [cycle](#def-b1-graph-traversals-path) code/bachelor-1/24-graph-traversals/listings/bipartite.py*

```
$ python bipartite.py
not bipartite: odd cycle of length 3: 5 - 1 - 12
```

***Output 24.6.** The friendship [graph](#def-b1-graph-traversals-graph) is not [bipartite](#def-b1-graph-traversals-bipartite): three people are friends with one another.*

An odd [cycle](#def-b1-graph-traversals-path) is a *certificate*: anyone can check in a moment that it is a [cycle](#def-b1-graph-traversals-path) of the [graph](#def-b1-graph-traversals-graph) and that its length is odd, and no [two-colouring](https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic#def-b1-propositional-logic-colouring) survives it ([Exercise 24.12](#exo-b1-graph-traversals-12)).

## 24.5 Applications

**[Connected components](#def-b1-graph-traversals-connected).** One search from an unmarked [vertex](#def-b1-graph-traversals-graph) marks exactly its component; restarting from each unmarked [vertex](#def-b1-graph-traversals-graph) in turn finds them all, in time $O(n + m)$.

```python
def components(g):
    """The components, each a sorted list of vertices; one search per component."""
    seen, out = set(), []
    for s in g.vertices():
        if s in seen:
            continue
        seen.add(s)
        stack, comp = [s], []
        while stack:
            u = stack.pop()
            comp.append(u)
            for v in g.adj[u]:
                if v not in seen:
                    seen.add(v)
                    stack.append(v)
        out.append(sorted(comp))
    return out
```

***Listing 24.7.** The [connected components](#def-b1-graph-traversals-connected) code/bachelor-1/24-graph-traversals/listings/components.py*

```
$ python components.py
29 people: [1, 2, 3, 4, 5, 6] ... [37, 38, 39]
10 people: [15, 16, 17, 19, 21, 22, 23, 24, 26, 27]
 1 people: [40]
```

***Output 24.7.** The friendship [graph](#def-b1-graph-traversals-graph) has three components; the third is person 40 alone.*

![The friendship graph, drawn by figures/town_graphs.py: people 1–14, 15–27 and 28–39 on three circles, person 40 apart; the bridges are thick.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-graph-traversals/fig-0177eb45acb4.svg)

*The friendship [graph](#def-b1-graph-traversals-graph), drawn by `figures/town_graphs.py`: people 1–14, 15–27 and 28–39 on three circles, person 40 apart; the [bridges](#def-b1-graph-traversals-bridge) are thick.*

**[Topological order](#def-b1-graph-traversals-topo).**

**Definition 24.19 (Topological order).**

A *topological order* of a [directed graph](#def-b1-graph-traversals-graph) is an order of its [vertices](#def-b1-graph-traversals-graph) in which, for every [arc](#def-b1-graph-traversals-graph) $u \to v$, $u$ comes before $v$.

A [graph](#def-b1-graph-traversals-graph) with a [cycle](#def-b1-graph-traversals-path) has none: the first [vertex](#def-b1-graph-traversals-graph) of the [cycle](#def-b1-graph-traversals-path) in the order would come after its predecessor on the [cycle](#def-b1-graph-traversals-path). A DAG has one, and [depth-first search](#def-b1-graph-traversals-dfs) finds it.

**Proposition 24.20 (Order by decreasing finishing time).**

In a [depth-first search](#def-b1-graph-traversals-dfs) of a DAG, $f(v) < f(u)$ for every [arc](#def-b1-graph-traversals-graph) $u \to v$. So the [vertices](#def-b1-graph-traversals-graph) by decreasing [finishing time](#def-b1-graph-traversals-dfs) are in [topological order](#def-b1-graph-traversals-topo).

**Proof.** When $u \to v$ is examined, $v$ is not open: it would be an ancestor of $u$ and the [arc](#def-b1-graph-traversals-graph) a [back edge](#def-b1-graph-traversals-edge-classes), which a DAG does not have ([Proposition 24.16](#prop-b1-graph-traversals-back)). If $v$ is unmarked, it becomes a descendant of $u$ and finishes first ([Theorem 24.15](#thm-b1-graph-traversals-parenthesis)); if it is finished, it finished before $u$, which is still open. ∎

Kahn’s method works from the other end: a DAG has a [vertex](#def-b1-graph-traversals-graph) with no incoming [arc](#def-b1-graph-traversals-graph) (follow [arcs](#def-b1-graph-traversals-graph) backwards from any [vertex](#def-b1-graph-traversals-graph); without a [cycle](#def-b1-graph-traversals-path) the walk must stop). Output one, remove it with its [arcs](#def-b1-graph-traversals-graph), and repeat. With [in-degrees](#def-b1-graph-traversals-degree) counted once and decreased as [vertices](#def-b1-graph-traversals-graph) go, it runs in $O(n + m)$; if [vertices](#def-b1-graph-traversals-graph) remain that all have incoming [arcs](#def-b1-graph-traversals-graph), there is a [cycle](#def-b1-graph-traversals-path).

```python
def by_dfs(g):
    """Vertices by decreasing finishing time."""
    done, order = set(), []

    def visit(u):
        done.add(u)
        for v in g.adj[u]:
            if v not in done:
                visit(v)
        order.append(u)  # u finishes after everything reachable from it

    for s in g.vertices():
        if s not in done:
            visit(s)
    return order[::-1]


def by_kahn(g):
    indegree = {v: 0 for v in g.vertices()}
    for _, v in g.edges():
        indegree[v] += 1
    ready = deque(v for v in g.vertices() if indegree[v] == 0)
    order = []
    while ready:
        u = ready.popleft()
        order.append(u)
        for v in g.adj[u]:  # removing u: its successors lose an incoming arc
            indegree[v] -= 1
            if indegree[v] == 0:
                ready.append(v)
    return order if len(order) == len(indegree) else None  # None: a cycle remains
```

***Listing 24.8.** A [topological order](#def-b1-graph-traversals-topo), by [depth-first search](#def-b1-graph-traversals-dfs) and by Kahn’s method code/bachelor-1/24-graph-traversals/listings/topo.py*

```
$ python topo.py
depth-first, topological: True
  induction correctness complexity sorting types functions
  pointers arrays memory lists hashing graphs
Kahn, topological: True
  types induction functions correctness pointers complexity
  memory arrays sorting lists hashing graphs
```

***Output 24.8.** Some chapters of this book in an order that respects which relies on which: two different orders, both valid.*

**[Strongly connected components](#def-b1-graph-traversals-connected).**

**Definition 24.21 (Component graph).**

The *component graph*, or *condensation*, of a [directed graph](#def-b1-graph-traversals-graph) has its [strongly connected components](#def-b1-graph-traversals-connected) as [vertices](#def-b1-graph-traversals-graph), and an [arc](#def-b1-graph-traversals-graph) $C \to C'$ when some [arc](#def-b1-graph-traversals-graph) of the [graph](#def-b1-graph-traversals-graph) goes from $C$ to $C' \neq C$.

The [component graph](#def-b1-graph-traversals-condensation) is a DAG: a [cycle](#def-b1-graph-traversals-path) through $C$ and $C'$ would make their [vertices](#def-b1-graph-traversals-graph) reachable from one another, so $C = C'$. A search started in a component with no [arc](#def-b1-graph-traversals-graph) leaving it in the [component graph](#def-b1-graph-traversals-condensation) marks exactly that component; the difficulty is to find such a component first.

**Method 24.22 (Kosaraju’s algorithm).**

1. Run a [depth-first search](#def-b1-graph-traversals-dfs) of $G$ and list the [vertices](#def-b1-graph-traversals-graph) by decreasing [finishing time](#def-b1-graph-traversals-dfs) .
2. Reverse every [arc](#def-b1-graph-traversals-graph) of $G$ .
3. In the reversed [graph](#def-b1-graph-traversals-graph) , take the [vertices](#def-b1-graph-traversals-graph) in that list; from each one not yet assigned, search, and assign every [vertex](#def-b1-graph-traversals-graph) reached that is not yet assigned to a new component.

```python
def finishing_order(g):
    done, order = set(), []
    for s in g.vertices():
        if s in done:
            continue
        done.add(s)
        stack = [(s, iter(g.adj[s]))]  # iterative DFS: a vertex and its unexplored arcs
        while stack:
            u, arcs = stack[-1]
            for v in arcs:
                if v not in done:
                    done.add(v)
                    stack.append((v, iter(g.adj[v])))
                    break
            else:  # no arc left: u finishes
                stack.pop()
                order.append(u)
    return order


def kosaraju(g):
    """Components as lists; the first search orders, the second, on the reversed graph,
    collects. Components come out in a topological order of the component graph."""
    r, comps, assigned = g.reversed(), [], set()
    for s in reversed(finishing_order(g)):  # by decreasing finishing time
        if s in assigned:
            continue
        assigned.add(s)
        comp, stack = [], [s]
        while stack:
            u = stack.pop()
            comp.append(u)
            for v in r.adj[u]:
                if v not in assigned:
                    assigned.add(v)
                    stack.append(v)
        comps.append(sorted(comp))
    return comps
```

***Listing 24.9.** Kosaraju’s algorithm, with an iterative search for the finishing order code/bachelor-1/24-graph-traversals/listings/kosaraju.py*

```
$ python kosaraju.py
small graph: ['abc', 'de', 'fg', 'h']
roads, road 1 one-way: [30] (sizes)
every road one-way as listed: 30 components, largest 1
```

***Output 24.9.** The small [graph](#def-b1-graph-traversals-graph) of the figure below; the roads with their one one-way street, and with every road one-way in the direction the table lists it.*

The answer to the first question is yes: with road 1 one-way, the thirty places form a single [strongly connected component](#def-b1-graph-traversals-connected). The second question needs care: making each road one-way in the direction the table happens to list it leaves every place alone in its component, since the table lists each road from the smaller place number to the larger, which makes a DAG.

**Lemma 24.23 (Finishing times and components).**

If $C$ and $C'$ are distinct [strongly connected components](#def-b1-graph-traversals-connected) and some [arc](#def-b1-graph-traversals-graph) goes from $C$ to $C'$, the largest [finishing time](#def-b1-graph-traversals-dfs) in $C$ is larger than the largest in $C'$.

**Proof.** Let $x$ be the first [vertex](#def-b1-graph-traversals-graph) of $C \cup C'$ discovered. If $x \in C$, every [vertex](#def-b1-graph-traversals-graph) of $C \cup C'$ is reachable from $x$ through unmarked [vertices](#def-b1-graph-traversals-graph), so all are descendants of $x$ and finish before it. If $x \in C'$, no [vertex](#def-b1-graph-traversals-graph) of $C$ is reachable from $x$ (or $C$ and $C'$ would merge), so all of $C'$ finishes, as descendants of $x$, before any [vertex](#def-b1-graph-traversals-graph) of $C$ is discovered. ∎

The proof that Kosaraju’s algorithm is correct is [Exercise 24.10](#exo-b1-graph-traversals-10): the [vertex](#def-b1-graph-traversals-graph) with the largest [finishing time](#def-b1-graph-traversals-dfs) lies in a component with no [arc](#def-b1-graph-traversals-graph) entering it, and in the reversed [graph](#def-b1-graph-traversals-graph) that component has no [arc](#def-b1-graph-traversals-graph) leaving it. Both searches cost $O(n + m)$, and so does reversing the [graph](#def-b1-graph-traversals-graph).

![Left, a directed graph and its four strongly connected components (shaded); right, its component graph, a DAG. Kosaraju’s second search, on the reversed arcs, starts in abc, which no arc enters: reversed, no arc leaves it, so the search stays inside.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-graph-traversals/fig-87a16535c498.svg)

*Left, a [directed graph](#def-b1-graph-traversals-graph) and its four [strongly connected components](#def-b1-graph-traversals-connected) (shaded); right, its [component graph](#def-b1-graph-traversals-condensation), a DAG. Kosaraju’s second search, on the reversed [arcs](#def-b1-graph-traversals-graph), starts in `abc`, which no [arc](#def-b1-graph-traversals-graph) enters: reversed, no [arc](#def-b1-graph-traversals-graph) leaves it, so the search stays inside.*

**[Bridges](#def-b1-graph-traversals-bridge).**

**Definition 24.24 (Bridge).**

A *bridge* of an undirected [graph](#def-b1-graph-traversals-graph) is an edge whose removal increases the number of [connected components](#def-b1-graph-traversals-connected).

An edge is a [bridge](#def-b1-graph-traversals-bridge) exactly when it lies on no [cycle](#def-b1-graph-traversals-path): if $uv$ is on a [cycle](#def-b1-graph-traversals-path), the rest of the [cycle](#def-b1-graph-traversals-path) still joins $u$ and $v$; if it is not, no other [path](#def-b1-graph-traversals-path) joins them. In a [depth-first search](#def-b1-graph-traversals-dfs) of an undirected [graph](#def-b1-graph-traversals-graph) there are no [cross edges](#def-b1-graph-traversals-edge-classes) (an edge to a finished [vertex](#def-b1-graph-traversals-graph) not a descendant would have been taken from the earlier one), so every non-tree edge joins a [vertex](#def-b1-graph-traversals-graph) to an ancestor. Let $\mathrm{low}(v)$ be the smallest [discovery time](#def-b1-graph-traversals-dfs) reachable from the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of $v$ by going down [tree edges](#def-b1-graph-traversals-edge-classes) and then along at most one other edge. A [tree edge](#def-b1-graph-traversals-edge-classes) $u v$, with $u$ the parent, is on a [cycle](#def-b1-graph-traversals-path) exactly when some edge leaves the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of $v$ for $u$ or above, that is when $\mathrm{low}(v) \leq d(u)$. The low points are computed on the way back up, in one search.

**Theorem 24.25 (Robbins’ theorem).**

The [edges](#def-b1-graph-traversals-graph) of a [connected](#def-b1-graph-traversals-connected) undirected [graph](#def-b1-graph-traversals-graph) can be oriented so that the resulting [directed graph](#def-b1-graph-traversals-graph) is [strongly connected](#def-b1-graph-traversals-connected) if and only if the [graph](#def-b1-graph-traversals-graph) has no [bridge](#def-b1-graph-traversals-bridge).

Robbins proved it in 1939, in a paper whose title names its application, traffic control. The proof, the [bridges](#def-b1-graph-traversals-bridge) and the orientation of Brenmoor’s roads are the weekend problem.

## 24.6 Exercises

**Exercise 24.1 ★.**

A [graph](#def-b1-graph-traversals-graph) on the [vertices](#def-b1-graph-traversals-graph) 1 to 6 has the [edges](#def-b1-graph-traversals-graph) $12, 13, 23, 24, 35, 45, 56$. Give the [degrees](#def-b1-graph-traversals-degree), check the handshake lemma, and list the [vertices](#def-b1-graph-traversals-graph) of odd [degree](#def-b1-graph-traversals-degree).

**Solution of Exercise 24.1.**

$\deg 1 = 2$, $\deg 2 = 3$, $\deg 3 = 3$, $\deg 4 = 2$, $\deg 5 = 3$, $\deg 6 = 1$: the sum is $14 = 2 \times 7$. The [vertices](#def-b1-graph-traversals-graph) of odd [degree](#def-b1-graph-traversals-degree) are 2, 3, 5 and 6: four of them, an even number.

**Exercise 24.2 ★.**

Run `dfs` on the [arcs](#def-b1-graph-traversals-graph) $1 \to 2$, $1 \to 3$, $2 \to 4$, $3 \to 4$, $4 \to 1$, $3 \to 5$, $5 \to 6$, $6 \to 5$, added in this order. Give the times and the class of each [arc](#def-b1-graph-traversals-graph).

**Solution of Exercise 24.2.**

Times $d|f$: $1$: $1|12$, $2$: $2|5$, $4$: $3|4$, $3$: $6|11$, $5$: $7|10$, $6$: $8|9$. [Tree edges](#def-b1-graph-traversals-edge-classes) $1 \to 2$, $2 \to 4$, $1 \to 3$, $3 \to 5$, $5 \to 6$; [back edges](#def-b1-graph-traversals-edge-classes) $4 \to 1$ and $6 \to 5$; [cross edge](#def-b1-graph-traversals-edge-classes) $3 \to 4$ (4 is finished and was discovered before 3); no [forward edge](#def-b1-graph-traversals-edge-classes).

**Exercise 24.3 ★.**

Give the [distances](#def-b1-graph-traversals-distance) from [vertex](#def-b1-graph-traversals-graph) 1 in the [graph](#def-b1-graph-traversals-graph) of [Exercise 24.1](#exo-b1-graph-traversals-1), and a [BFS tree](#def-b1-graph-traversals-bfs).

**Solution of Exercise 24.3.**

$\delta(1, 1) = 0$; $\delta(1, 2) = \delta(1, 3) = 1$; $\delta(1, 4) = \delta(1, 5) = 2$; $\delta(1, 6) = 3$. With neighbours taken in increasing order, the [BFS tree](#def-b1-graph-traversals-bfs) has the [edges](#def-b1-graph-traversals-graph) $12, 13, 24, 35, 56$.

**Exercise 24.4 ★.**

Dinner: boiling water comes before cooking pasta, chopping onions before frying them, the fried onions and an opened tin before the sauce, the pasta and the sauce before serving. Give a [topological order](#def-b1-graph-traversals-topo) by Kahn’s method and one by [depth-first search](#def-b1-graph-traversals-dfs).

**Solution of Exercise 24.4.**

With the tasks in the order they first appear, Kahn’s method gives boil, chop, tin, pasta, fry, sauce, serve. A [depth-first search](#def-b1-graph-traversals-dfs) gives, by decreasing [finishing time](#def-b1-graph-traversals-dfs), tin, chop, fry, sauce, boil, pasta, serve. Both put each task after the ones it needs.

**Exercise 24.5 ★★.**

This search marks a [vertex](#def-b1-graph-traversals-graph) only when its visit ends. Explain the two lines of output; what happens on a [graph](#def-b1-graph-traversals-graph) with a [cycle](#def-b1-graph-traversals-path), and why does a DAG survive?

```python
def search(g, u, done):
    global visits
    visits += 1
    for v in g.adj[u]:
        if v not in done:
            search(g, v, done)
    done.add(u)  # marked on exit only
```

***Listing 24.10.** Marked on exit code/bachelor-1/24-graph-traversals/listings/exo_mark_exit.py*

```
10 diamonds, no cycle: 31 vertices, 31 visits
a cycle x -> y -> x: RecursionError
```

***Output 24.10.** A chain of ten diamonds, and a [two-vertex](#def-b1-graph-traversals-graph) [cycle](#def-b1-graph-traversals-path). Some lines are left out.*

**Solution of Exercise 24.5.**

A [vertex](#def-b1-graph-traversals-graph) is unmarked while it is open. On a DAG the search never meets an open [vertex](#def-b1-graph-traversals-graph) again (that would be a [back edge](#def-b1-graph-traversals-edge-classes)), and a finished [vertex](#def-b1-graph-traversals-graph) is marked: each [vertex](#def-b1-graph-traversals-graph) is visited once, 31 visits for 31 [vertices](#def-b1-graph-traversals-graph). On a [cycle](#def-b1-graph-traversals-path), the search comes back to an open [vertex](#def-b1-graph-traversals-graph), which is not marked, and starts it again: $x$, $y$, $x$, $y$, …, until the call [stack overflows](https://one-course.com/books/computer-science/3/en/chapter/3-functions-and-the-call-stack#def-b1-c-functions-and-stack-stack-overflow). Marking on entry, as `dfs` does, fixes it.

**Exercise 24.6 ★★.**

Find the [graph](#def-b1-graph-traversals-graph) this test misjudges, and repair it.

```python
def bipartite_from_first(g):
    first = g.vertices()[0]
    colour, queue = {first: 0}, deque([first])
    while queue:
        u = queue.popleft()
        for v in g.adj[u]:
            if v not in colour:
                colour[v] = 1 - colour[u]
                queue.append(v)
            elif colour[v] == colour[u]:
                return False
    return True
```

***Listing 24.11.** A [bipartite](#def-b1-graph-traversals-bipartite) test code/bachelor-1/24-graph-traversals/listings/exo_bipartite_one.py*

```
bipartite? True
```

***Output 24.11.** A [path](#def-b1-graph-traversals-path) 1–2–3–4 and a triangle 5, 6, 7. Some lines are left out.*

**Solution of Exercise 24.6.**

The search starts from the first [vertex](#def-b1-graph-traversals-graph) only, so it colours the [path](#def-b1-graph-traversals-path) 1–2–3–4 and never sees the triangle, an odd [cycle](#def-b1-graph-traversals-path). Starting a search from every uncoloured [vertex](#def-b1-graph-traversals-graph), as `two_colour` does, repairs it; the cost stays $O(n + m)$.

**Exercise 24.7 ★★.**

Modify [breadth-first search](#def-b1-graph-traversals-bfs) to count, for every [vertex](#def-b1-graph-traversals-graph) $v$, the shortest [paths](#def-b1-graph-traversals-path) from $s$ to $v$, in time $O(n + m)$.

**Solution of Exercise 24.7.**

```python
def count_shortest(adj, s):
    dist, ways = {s: 0}, {s: 1}
    queue = deque([s])
    while queue:
        u = queue.popleft()
        for v in adj[u]:
            if v not in dist:
                dist[v], ways[v] = dist[u] + 1, 0
                queue.append(v)
            if dist[v] == dist[u] + 1:  # u is a predecessor of v on a shortest path
                ways[v] += ways[u]
    return dist, ways
```

*Counting shortest [paths](#def-b1-graph-traversals-path) code/bachelor-1/24-graph-traversals/exercises/count_paths.py*

A shortest [path](#def-b1-graph-traversals-path) to $v$ ends with an edge $u v$ where $\delta(s, u) = \delta(s, v) - 1$, and those [paths](#def-b1-graph-traversals-path) are counted by the sum of the counts of such $u$. Every such $u$ leaves the queue before $v$ does, and each of its predecessors left before it: its count is final when it is added. The test compares with an enumeration of the [paths](#def-b1-graph-traversals-path) on random [graphs](#def-b1-graph-traversals-graph).

**Exercise 24.8 ★★.**

Write a function that returns a [cycle](#def-b1-graph-traversals-path) of a [directed graph](#def-b1-graph-traversals-graph), as a list of [vertices](#def-b1-graph-traversals-graph), or `None` if the [graph](#def-b1-graph-traversals-graph) is acyclic, in time $O(n + m)$.

**Solution of Exercise 24.8.**

```python
def find_cycle(adj):
    state, parent = {}, {}  # state: 1 open, 2 finished

    def visit(u):
        state[u] = 1
        for v in adj[u]:
            if state.get(v) == 1:  # a back edge u -> v closes a cycle v ... u
                cycle = [u]
                while cycle[-1] != v:
                    cycle.append(parent[cycle[-1]])
                return cycle[::-1]
            if v not in state:
                parent[v] = u
                found = visit(v)
                if found:
                    return found
        state[u] = 2
        return None

    for s in adj:
        if s not in state:
            found = visit(s)
            if found:
                return found
    return None
```

*A [cycle](#def-b1-graph-traversals-path), from the first [back edge](#def-b1-graph-traversals-edge-classes) code/bachelor-1/24-graph-traversals/exercises/find_cycle.py*

By [Proposition 24.16](#prop-b1-graph-traversals-back), a [cycle](#def-b1-graph-traversals-path) exists exactly when the search meets a [back edge](#def-b1-graph-traversals-edge-classes) $u \to v$; the parents lead from $u$ up to $v$, and reversed they give the [cycle](#def-b1-graph-traversals-path). The search is $O(n + m)$, and the [cycle](#def-b1-graph-traversals-path) is built once.

**Exercise 24.9 ★★.**

Show that a [free tree](#def-b1-graph-traversals-free-tree) with $n$ [vertices](#def-b1-graph-traversals-graph) has $n - 1$ [edges](#def-b1-graph-traversals-graph), and that a [connected graph](#def-b1-graph-traversals-connected) with $n$ [vertices](#def-b1-graph-traversals-graph) and $n - 1$ [edges](#def-b1-graph-traversals-graph) is a [free tree](#def-b1-graph-traversals-free-tree).

**Solution of Exercise 24.9.**

By induction on $n$; true for $n = 1$. A [free tree](#def-b1-graph-traversals-free-tree) with $n \geq 2$ [vertices](#def-b1-graph-traversals-graph) has a [vertex](#def-b1-graph-traversals-graph) of [degree](#def-b1-graph-traversals-degree) 1: the end $x$ of a longest [simple path](#def-b1-graph-traversals-path) has a neighbour on the [path](#def-b1-graph-traversals-path), and no other, since another neighbour on the [path](#def-b1-graph-traversals-path) would close a [cycle](#def-b1-graph-traversals-path) and one off it would give a longer [path](#def-b1-graph-traversals-path). Removing $x$ and its edge leaves a [free tree](#def-b1-graph-traversals-free-tree) on $n - 1$ [vertices](#def-b1-graph-traversals-graph), with $n - 2$ [edges](#def-b1-graph-traversals-graph) by induction: $n - 1$ in all. Conversely, take a [connected graph](#def-b1-graph-traversals-connected) with $n$ [vertices](#def-b1-graph-traversals-graph) and $n - 1$ [edges](#def-b1-graph-traversals-graph); while it has a [cycle](#def-b1-graph-traversals-path), remove an edge of a [cycle](#def-b1-graph-traversals-path), which keeps it [connected](#def-b1-graph-traversals-connected). The result is a [free tree](#def-b1-graph-traversals-free-tree), with $n - 1$ [edges](#def-b1-graph-traversals-graph): no edge was removed, so there was no [cycle](#def-b1-graph-traversals-path).

**Exercise 24.10 ★★★.**

Prove that Kosaraju’s algorithm finds the [strongly connected components](#def-b1-graph-traversals-connected).

**Solution of Exercise 24.10.**

We show by induction that each search of the second pass assigns exactly one [strongly connected component](#def-b1-graph-traversals-connected). Suppose the assigned [vertices](#def-b1-graph-traversals-graph) are a union of components, and the search starts from $s$, the unassigned [vertex](#def-b1-graph-traversals-graph) with the largest [finishing time](#def-b1-graph-traversals-dfs), in the component $C$. Reversing [arcs](#def-b1-graph-traversals-graph) keeps components, and none of $C$ is assigned, so the search reaches all of $C$. Suppose it leaves $C$: the first [vertex](#def-b1-graph-traversals-graph) reached outside $C$, in a component $C'$ not assigned, is reached by a reversed [arc](#def-b1-graph-traversals-graph), that is, an [arc](#def-b1-graph-traversals-graph) of $G$ from $C'$ to $C$. By [Lemma 24.23](#lem-b1-graph-traversals-finish) some [vertex](#def-b1-graph-traversals-graph) of $C'$ finishes after every [vertex](#def-b1-graph-traversals-graph) of $C$, so after $s$: impossible, since $s$ has the largest [finishing time](#def-b1-graph-traversals-dfs) among the unassigned [vertices](#def-b1-graph-traversals-graph). So the search assigns exactly $C$, and the induction goes on.

**Exercise 24.11 ★★★.**

An *Euler circuit* goes along every edge of a [graph](#def-b1-graph-traversals-graph) exactly once and returns to its start. Write a function that finds one in a [connected graph](#def-b1-graph-traversals-connected) whose [degrees](#def-b1-graph-traversals-degree) are all even, in time $O(n + m)$, and test it.

**Solution of Exercise 24.11.**

```python
def euler_circuit(edges, start):
    """edges: list of (u, v), undirected. Returns the circuit as a list of vertices."""
    adj = {}
    for i, (u, v) in enumerate(edges):
        adj.setdefault(u, []).append((v, i))
        adj.setdefault(v, []).append((u, i))
    used, stack, circuit = set(), [start], []
    while stack:
        u = stack[-1]
        while adj[u] and adj[u][-1][1] in used:
            adj[u].pop()  # drop edges already walked
        if adj[u]:
            v, i = adj[u].pop()
            used.add(i)
            stack.append(v)  # walk on
        else:
            circuit.append(stack.pop())  # stuck: u is final, back up
    return circuit[::-1]
```

*Hierholzer’s method code/bachelor-1/24-graph-traversals/exercises/euler.py*

Since every [degree](#def-b1-graph-traversals-degree) is even, a walk that enters a [vertex](#def-b1-graph-traversals-graph) other than its start can leave it again: the walk gets stuck only at the [vertex](#def-b1-graph-traversals-graph) where its current part began. When the top of the stack has no edge left, it is placed in the circuit, and the walk resumes from the [vertex](#def-b1-graph-traversals-graph) below; the circuit, read backwards, is a single closed walk with every detour spliced in where it started. Each edge is pushed and popped once: $O(n + m)$. The test builds [graphs](#def-b1-graph-traversals-graph) as unions of random closed walks, whose [degrees](#def-b1-graph-traversals-degree) are all even, and checks that the circuit uses each edge once.

**Exercise 24.12 ★★★.**

Prove that an undirected [graph](#def-b1-graph-traversals-graph) is [bipartite](#def-b1-graph-traversals-bipartite) if and only if it has no [cycle](#def-b1-graph-traversals-path) of odd length.

**Solution of Exercise 24.12.**

If $G$ is two-coloured, the colours alternate along a [cycle](#def-b1-graph-traversals-path), which returns to its first colour after an even number of steps. Conversely, suppose $G$ has no odd [cycle](#def-b1-graph-traversals-path), and colour each component by the parity of the [distance](#def-b1-graph-traversals-distance) from a [vertex](#def-b1-graph-traversals-graph) $s$ found by [breadth-first search](#def-b1-graph-traversals-bfs). If an edge $u v$ joins two [vertices](#def-b1-graph-traversals-graph) of the same colour, let $w$ be the last common [vertex](#def-b1-graph-traversals-graph) of the tree [paths](#def-b1-graph-traversals-path) from $s$ to $u$ and to $v$. The tree [paths](#def-b1-graph-traversals-path) from $w$ to $u$ and to $v$ share only $w$, and their lengths $\delta(s, u) - \delta(s, w)$ and $\delta(s, v) - \delta(s, w)$ have the same parity; with $u v$ they form a [cycle](#def-b1-graph-traversals-path) of odd length, a contradiction.

## 24.7 Problem: Robbins’ town

**Problem 24.1.**

Weekend problem — Robbins’ town

The town council of Brenmoor wants every road one-way, and every place still reachable from every other. Before the roads, the friendship [graph](#def-b1-graph-traversals-graph) serves as a warm-up.

```python
def bridges(g):
    """low[v]: the smallest discovery time reachable from v's subtree by tree edges down
    and at most one other edge. A tree edge uv is a bridge iff low[v] > disc[u]."""
    disc, low, out = {}, {}, []
    clock = 0

    def visit(u, parent_edge):
        nonlocal clock
        clock += 1
        disc[u] = low[u] = clock
        for v in g.adj[u]:
            if (v, u) == parent_edge:  # do not go back along the tree edge itself
                parent_edge = None  # (only once: a parallel edge would count)
                continue
            if v in disc:
                low[u] = min(low[u], disc[v])
            else:
                visit(v, (u, v))
                low[u] = min(low[u], low[v])
                if low[v] > disc[u]:
                    out.append((u, v))

    for s in g.vertices():
        if s not in disc:
            visit(s, None)
    return out
```

***Listing 24.12.** [Bridges](#def-b1-graph-traversals-bridge) by low points code/bachelor-1/24-graph-traversals/listings/bridges.py*

```
$ python bridges.py
friendships: 12 bridges
  4-9 12-20 15-27 16-21 18-20 22-27 23-24 23-26 25-37 29-31 33-35 33-39
roads: 0 bridges (53 roads between 30 places)
```

***Output 24.12.** [Bridges](#def-b1-graph-traversals-bridge) among friends, and among roads.*

```python
def orient(g):
    """A strongly connected orientation of a connected graph without bridges."""
    disc, arcs = {}, Graph(directed=True)
    for v in g.vertices():
        arcs.add_vertex(v)

    def visit(u):
        disc[u] = len(disc)
        for v in g.adj[u]:
            if v not in disc:
                arcs.add_edge(u, v)  # tree edge: from parent to child
                visit(v)
            elif disc[v] < disc[u] and v not in arcs.adj[u] and u not in arcs.adj[v]:
                arcs.add_edge(u, v)  # back edge: from descendant up to ancestor

    visit(g.vertices()[0])
    return arcs
```

***Listing 24.13.** Orienting the roads by a [depth-first search](#def-b1-graph-traversals-dfs) code/bachelor-1/24-graph-traversals/listings/orient.py*

```
$ python orient.py
53 one-way roads for 53 roads; strongly connected components: 1
road 1 goes from 1 to 3, as now
```

***Output 24.13.** Every road one-way, and the town still [strongly connected](#def-b1-graph-traversals-connected).*

**Part I — The friendship graph.**

1. Using [Output 24.1](#out-b1-graph-traversals-graph) , how many friendships does person 40 have, and what is the average [degree](#def-b1-graph-traversals-degree) ?
2. Why does [Output 24.7](#out-b1-graph-traversals-components) count person 40 as a component?
3. What do the components tell about the three groups of friends drawn in [Section 24.5](#sec-24-5) ?
4. Why does the triangle of [Output 24.6](#out-b1-graph-traversals-bipartite) prove that the [graph](#def-b1-graph-traversals-graph) is not [bipartite](#def-b1-graph-traversals-bipartite) ?
5. Could two of the components be [bipartite](#def-b1-graph-traversals-bipartite) while the whole [graph](#def-b1-graph-traversals-graph) is not? What would the program print?
6. What is the cost of the component and [bipartite](#def-b1-graph-traversals-bipartite) searches, in $n$ and $m$ ?

**Part II — The roads and the one-way street.**

7. How many [arcs](#def-b1-graph-traversals-graph) would the road [graph](#def-b1-graph-traversals-graph) have if road 1 were two-way?
8. Explain the single component of [Output 24.9](#out-b1-graph-traversals-kosaraju) : which [path](#def-b1-graph-traversals-path) leads from the Library back to the Town Square?
9. Why does listing each road from its smaller place number make a DAG, and why does a DAG have only components of one [vertex](#def-b1-graph-traversals-graph) ?
10. In the [component graph](#def-b1-graph-traversals-condensation) of the roads oriented as listed, which [vertices](#def-b1-graph-traversals-graph) have no incoming [arc](#def-b1-graph-traversals-graph) ?
11. What is the cost of Kosaraju’s algorithm on the roads?
12. Why does reversing every [arc](#def-b1-graph-traversals-graph) leave the [strongly connected components](#def-b1-graph-traversals-connected) unchanged?

**Part III — Bridges.**

13. Show that an edge is a [bridge](#def-b1-graph-traversals-bridge) if and only if it lies on no [cycle](#def-b1-graph-traversals-path) .
14. Why does a [depth-first search](#def-b1-graph-traversals-dfs) of an undirected [graph](#def-b1-graph-traversals-graph) have no [cross edges](#def-b1-graph-traversals-edge-classes) ?
15. Prove that a [tree edge](#def-b1-graph-traversals-edge-classes) $u v$ , $u$ the parent, is a [bridge](#def-b1-graph-traversals-bridge) if and only if $\mathrm{low}(v) > d(u)$ .
16. Why does `visit` skip the edge back to the parent, and only once?
17. The friendship [graph](#def-b1-graph-traversals-graph) has 12 [bridges](#def-b1-graph-traversals-bridge) : what do they say about the groups of friends?
18. Why can the road [graph](#def-b1-graph-traversals-graph) have no [bridge](#def-b1-graph-traversals-bridge) , given how its roads were laid (each place joined to its three nearest)? Is this a proof?

**Part IV — Robbins’ theorem.**

19. Show that a [graph](#def-b1-graph-traversals-graph) with a [bridge](#def-b1-graph-traversals-bridge) has no [strongly connected](#def-b1-graph-traversals-connected) orientation.
20. In `orient` , why is every edge oriented exactly once?
21. Show that in the orientation, every [vertex](#def-b1-graph-traversals-graph) is reachable from the root.
22. Show that, if the [graph](#def-b1-graph-traversals-graph) has no [bridge](#def-b1-graph-traversals-bridge) , the root is reachable from every [vertex](#def-b1-graph-traversals-graph) in the orientation.
23. Deduce Robbins’ theorem.
24. Why does road 1 keep the direction it has today?
25. State the named result, *Robbins’ theorem* , and what the program checked on Brenmoor.

**Solution of Problem 24.1.**

**1.** None: the smallest [degree](#def-b1-graph-traversals-degree) is 0, and person 40 has it. The average [degree](#def-b1-graph-traversals-degree) is $100 / 40 = 2.5$.

**2.** A component is a class of the relation “reachable from”; nobody is reachable from person 40 but person 40.

**3.** The groups 1–14 and 28–39 are joined by two friendships ($1$–$28$ and $5$–$37$) into one component, together with three people of the middle group (18, 20 and 25), whose friends are on that side. The ten others of the middle group form a component of their own.

**4.** A triangle is a [cycle](#def-b1-graph-traversals-path) of length 3; the colours would alternate along it and return to the first colour after three steps, which is impossible.

**5.** Yes: a [graph](#def-b1-graph-traversals-graph) is [bipartite](#def-b1-graph-traversals-bipartite) exactly when all its components are. The program would print an odd [cycle](#def-b1-graph-traversals-path) of the component that is not.

**6.** $O(n + m)$: each [vertex](#def-b1-graph-traversals-graph) enters the queue or the stack once, and each list of neighbours is read once.

**7.** 106: two for each of the 53 roads.

**8.** Every [arc](#def-b1-graph-traversals-graph) but $1 \to 3$ comes with its reverse, so every place still reaches the places it reached before, by going around road 1 if needed: from the Library, by the South [Bridge](#def-b1-graph-traversals-bridge) back to the Town Square.

**9.** Along any [path](#def-b1-graph-traversals-path) the place numbers increase, so no [path](#def-b1-graph-traversals-path) returns to its start: there is no [cycle](#def-b1-graph-traversals-path). Two distinct [vertices](#def-b1-graph-traversals-graph) that reach each other would make a [cycle](#def-b1-graph-traversals-path), so each component has one [vertex](#def-b1-graph-traversals-graph).

**10.** The [component graph](#def-b1-graph-traversals-condensation) is the DAG itself; the [vertices](#def-b1-graph-traversals-graph) without incoming [arcs](#def-b1-graph-traversals-graph) are the places never listed second: 1, 2, 4, 5, 6, 8 and 18.

**11.** $O(n + m)$ with $n = 30$ and $m = 105$, for each of the two searches and for reversing the [arcs](#def-b1-graph-traversals-graph).

**12.** A [path](#def-b1-graph-traversals-path) from $u$ to $v$ in $G$ is, reversed, a [path](#def-b1-graph-traversals-path) from $v$ to $u$ in the reversed [graph](#def-b1-graph-traversals-graph); reaching each other is unchanged.

**13.** If $u v$ lies on a [cycle](#def-b1-graph-traversals-path), the rest of the [cycle](#def-b1-graph-traversals-path) joins $u$ and $v$ after removing it, and every [path](#def-b1-graph-traversals-path) that used the edge can go around: the components stay the same. If $u v$ lies on no [cycle](#def-b1-graph-traversals-path), any other [path](#def-b1-graph-traversals-path) from $u$ to $v$ would close a [cycle](#def-b1-graph-traversals-path) with it; so removing it separates $u$ from $v$.

**14.** When an edge $u v$ is first examined from $u$, $v$ is either unmarked, and the edge becomes a [tree edge](#def-b1-graph-traversals-edge-classes), or open, an ancestor; if $v$ were finished, $u v$ would already have been examined from $v$, when $u$ was unmarked or open, so $u$ would be a descendant of $v$.

**15.** With no [cross edges](#def-b1-graph-traversals-edge-classes), every edge leaving the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of $v$ other than $u v$ goes to an ancestor of $v$, so to $u$ or above, with a [discovery time](#def-b1-graph-traversals-dfs) at most $d(u)$. Such an edge exists exactly when $\mathrm{low}(v) \leq d(u)$, and it closes a [cycle](#def-b1-graph-traversals-path) through $u v$ with tree [paths](#def-b1-graph-traversals-path). If none exists, every [path](#def-b1-graph-traversals-path) from the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) to the rest uses $u v$, which is a [bridge](#def-b1-graph-traversals-bridge).

**16.** The [tree edge](#def-b1-graph-traversals-edge-classes) itself would give $\mathrm{low}(v) \leq d(u)$ and hide every [bridge](#def-b1-graph-traversals-bridge). Only once, because a second edge between the same two [vertices](#def-b1-graph-traversals-graph) is a real [cycle](#def-b1-graph-traversals-path) of two [edges](#def-b1-graph-traversals-graph): in a road map, two parallel roads.

**17.** Ten of them join a person with a single friend, who would be cut off by losing that friendship; $12$–$20$ holds people 20 and 18 to the rest, and $33$–$39$ people 33 and 35. Inside the groups, no single friendship matters.

**18.** Joining each place to its three nearest makes [cycles](#def-b1-graph-traversals-path) likely, but two clusters could still be joined by a single road: it is not a proof. The program checked: 0 [bridges](#def-b1-graph-traversals-bridge).

**19.** Let $u v$ be a [bridge](#def-b1-graph-traversals-bridge), oriented $u \to v$. Every [path](#def-b1-graph-traversals-path) from the side of $v$ to the side of $u$ must use the edge, which points the other way: no orientation makes $u$ reachable from $v$.

**20.** An edge is examined from both ends. A [tree edge](#def-b1-graph-traversals-edge-classes) is added when the parent examines it; from the child, it is skipped, since the [arc](#def-b1-graph-traversals-graph) already exists. A non-tree edge joins a [vertex](#def-b1-graph-traversals-graph) to an ancestor; it is added when the descendant examines it, the ancestor being discovered earlier, and skipped from the ancestor, which has the larger [discovery time](#def-b1-graph-traversals-dfs) on that side of the test, or the [arc](#def-b1-graph-traversals-graph) already exists.

**21.** [Tree edges](#def-b1-graph-traversals-edge-classes) point from parent to child, so the tree [path](#def-b1-graph-traversals-path) from the root to any [vertex](#def-b1-graph-traversals-graph) is a directed [path](#def-b1-graph-traversals-path).

**22.** Let $v$ be a [vertex](#def-b1-graph-traversals-graph) other than the root, with parent $p$. The edge $p v$ is not a [bridge](#def-b1-graph-traversals-bridge), so by question 15 some edge goes from a [vertex](#def-b1-graph-traversals-graph) $x$ of the [subtree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) of $v$ to a proper ancestor $a$ of $v$. It is oriented upwards, $x \to a$, and tree [arcs](#def-b1-graph-traversals-graph) lead from $v$ down to $x$: $a$ is reachable from $v$, and $d(a) < d(v)$. Repeating from $a$, the [discovery times](#def-b1-graph-traversals-dfs) decrease, so the walk ends at the root.

**23.** A [bridge](#def-b1-graph-traversals-bridge) forbids a [strongly connected](#def-b1-graph-traversals-connected) orientation (question 19). Without a [bridge](#def-b1-graph-traversals-bridge), the orientation of `orient` lets every [vertex](#def-b1-graph-traversals-graph) reach the root and the root reach every [vertex](#def-b1-graph-traversals-graph), so every [vertex](#def-b1-graph-traversals-graph) reaches every other.

**24.** The search starts at the Town Square, place 1, and its first neighbour is the Library, place 3, since road 1 comes first in the table: $1 \to 3$ is a [tree edge](#def-b1-graph-traversals-edge-classes), oriented from parent to child.

**25.** *Robbins’ theorem*: a [connected graph](#def-b1-graph-traversals-connected) has a [strongly connected](#def-b1-graph-traversals-connected) orientation if and only if it has no [bridge](#def-b1-graph-traversals-bridge). Brenmoor’s road [graph](#def-b1-graph-traversals-graph) has no [bridge](#def-b1-graph-traversals-bridge), and the orientation computed makes all 53 roads one-way with a single [strongly connected component](#def-b1-graph-traversals-connected), checked by Kosaraju’s algorithm.
