Ciência da computação · Livro 3 · Graduação — Ano 1

University Computer Science — Year 1

Este livro ainda não está disponível em Português. Edições: English.

University Computer Science — Year 1 · Graduação — Ano 1

24Graphs 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, and both are answered by a program that walks the graph in a well-chosen order. This chapter builds the two walks, depth first and breadth first, and what they compute: distances, components, orders, and the roads that cannot be spared.

You already know

The second book drew graphs, computed distances in a graph by breadth-first search and routes by Dijkstra’s algorithm. The mathematics book represents a graph by its adjacency matrix. Stacks and queues were built in Chapter 15.

24.1 Definitions

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

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

Definition 24.2 (Degree)

The degree deg⁡(v)\deg(v) of a vertex of an undirected graph is the number of edges at vv; its neighbours are the other ends of these edges. In a directed graph, the out-degree of vv counts the arcs leaving vv, its in-degree those arriving at vv.

Proposition 24.3 (Handshake lemma)

In an undirected graph, ∑vdeg⁡(v)=2m\sum_v \deg(v) = 2m; so the number of vertices of odd degree is even. In a directed graph, the out-degrees and the in-degrees both sum to mm.

Proof. Each edge uvuv is counted twice in the sum, once in deg⁡(u)\deg(u) and once in deg⁡(v)\deg(v); each arc once among the out-degrees, at its tail, and once among the in-degrees, at its head. The sum of the even degrees is even, so the odd degrees have an even sum, which needs an even number of them. ∎

Definition 24.4 (Path, simple path, cycle)

A path of length kk from uu to vv is a sequence of vertices u=v0,v1,…,vk=vu = v_0, v_1, \dots, v_k = v where each vi−1viv_{i-1} v_i is an edge (an arc vi−1→viv_{i-1} \to v_i in a directed graph). It is simple if its vertices are distinct. A cycle is a path of length at least 1 from a vertex to itself whose other vertices are distinct and distinct from it; in an undirected graph its length must be at least 3 and it uses no edge twice. vv is reachable from uu if there is a path from uu to vv.

Definition 24.5 (Distance)

The distance δ(u,v)\delta(u, v) is the smallest length of a path from uu to vv, counted in edges, and ∞\infty if vv is not reachable from uu.

Definition 24.6 (Connected, strongly connected)

An undirected graph is connected if every vertex is reachable from every other. Being reachable from one another is an equivalence relation on the vertices; its classes are the connected components. In a directed graph, uu and vv are strongly connected when each is reachable from the other; the classes of this equivalence are the strongly connected components, and the 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 without a cycle.

Definition 24.8 (Free tree, forest)

A free tree is a connected undirected graph without a cycle; a forest is an undirected graph without a cycle, whose components are free trees. Choosing a vertex as the root turns a free tree into a rooted tree (Definition 11.2).

Proposition 24.9 (Free trees)

For an undirected graph GG with n≥1n \geq 1 vertices, the following are equivalent: (i) GG is a free tree; (ii) any two vertices are joined by exactly one simple path; (iii) GG is connected and has n−1n - 1 edges.

Proof. (i)⇒\Rightarrow(ii): a simple path exists, since GG is connected and a shortest path is simple. If two different simple paths join uu and vv, follow them from uu to the first vertex where they part, xx, and on the first one to the first vertex after xx that the second one also visits, yy; the two pieces from xx to yy share only their ends and make a cycle. (ii)⇒\Rightarrow(i): GG is connected, and a cycle through uvu v would give two simple paths from uu to vv, the edge and the rest of the cycle. (i)⇔\Leftrightarrow(iii) is Exercise 24.9. ∎

Definition 24.10 (Bipartite graph)

An undirected graph is bipartite if its vertices can be coloured with two colours so that every edge joins two vertices 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: a road’s length, a street’s name.

24.2 Representations and their costs

The mathematics book stores a graph in its adjacency matrix: an n×nn \times n table whose entry (u,v)(u, v) is 1 when uvu v is an edge. Programs more often keep, for each vertex, the list of its neighbours.

Definition 24.12 (Adjacency list, edge list)

The adjacency lists of a graph give, for each vertex, the list of its neighbours (in a directed graph, the heads of its arcs). Its edge list is the list of its edges, as pairs of vertices.

@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 as adjacency 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 of the town: each two-way road is two arcs, so the roads give 2×53−1=1052 \times 53 - 1 = 105 arcs.

The degrees of the friendship graph sum to 100, twice its 50 edges, as the handshake lemma says; the out-degrees of the road graph sum to its number of arcs.

adjacency matrixadjacency listsedge list
spaceΘ(n2)\Theta(n^2)Θ(n+m)\Theta(n + m)Θ(m)\Theta(m)
is uvu v an edge?O(1)O(1)O(deg⁡u)O(\deg u)O(m)O(m)
the neighbours of uuΘ(n)\Theta(n)Θ(deg⁡u)\Theta(\deg u)Θ(m)\Theta(m)
add an edgeO(1)O(1)O(1)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 and one per arc, twice as many per edge in an undirected graph.

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

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 written as an edge list 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 survives the round trip through a file.

The first line also lists the vertices, so that a vertex without edges, such as person 40 of the friendship 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 uu by marking it, then visiting in turn each unmarked neighbour of uu; on the whole graph, it visits each vertex not yet marked. A clock ticks at each start and each end of a visit: uu’s discovery time d(u)d(u) is the tick when its visit starts, its finishing time f(u)f(u) the tick when it ends. Between the two, uu is open. If the visit of uu calls the visit of vv, uu is the parent of vv; the parent links form the DFS forest.

Definition 24.14 (Classes of arcs)

In a depth-first search of a directed graph, an arc u→vu \to v is a tree edge if uu is the parent of vv; a back edge if vv is an ancestor of uu in the forest, or uu itself; a forward edge if vv is a descendant of uu but not its child; a cross edge otherwise.

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: times, and the class of each arc code/bachelor-1/24-graph-traversals/listings/dfs.py

When the arc u→vu \to v is examined, vv is unmarked (a tree edge), open (on the chain of visits in progress, so an ancestor: a back edge), or finished, and then a descendant of uu exactly when it was discovered after uu.

$ 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: 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.
The search of Output 24.4, started at a, then at e; each vertex carries d∣fd|f. The tree edges form two trees, rooted at a and e.

Theorem 24.15 (Parenthesis theorem)

For any two vertices uu and vv of a depth-first search, the intervals [d(u),f(u)][d(u), f(u)] and [d(v),f(v)][d(v), f(v)] are disjoint or one contains the other; and [d(v),f(v)]⊂[d(u),f(u)][d(v), f(v)] \subset [d(u), f(u)] exactly when vv is a descendant of uu, v≠uv \neq u.

Proof. Say d(u)<d(v)d(u) < d(v). If vv is discovered while uu is open, vv’s visit is called, directly or not, from uu’s, so vv is a descendant of uu; and a call returns before its caller does, so f(v)<f(u)f(v) < f(u): nested. Otherwise uu finished before d(v)d(v): disjoint. Conversely, a descendant of uu is discovered during uu’s visit, so its interval is nested in uu’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 vv is discovered, every vertex reachable from vv by a path of unmarked vertices becomes a descendant of vv (the white-path property; take the first vertex of such a path that would not be a descendant: its predecessor on the path is one, and examines it before finishing).

Proposition 24.16 (Cycles and back edges)

A directed graph is acyclic if and only if a depth-first search finds no back edge.

Proof. A back edge u→vu \to v, with vv an ancestor of uu, closes a cycle with the tree path from vv to uu. Conversely, let CC be a cycle and vv its first vertex to be discovered, and u→vu \to v the arc of CC that enters vv. At d(v)d(v) the rest of CC is unmarked, so uu becomes a descendant of vv by the white-path property, and u→vu \to v is a back edge. ∎

The recursive search can run out of Python’s call stack on a long path. An explicit stack does the same work in a loop; pushing all the neighbours at once, it discovers the vertices in the same order, but it no longer knows when a vertex finishes. For finishing times, the stack holds each open vertex with the iterator over its remaining arcs (Listing 24.9).

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 ss keeps a queue of discovered vertices, initially ss; it removes the vertex uu at the head and discovers each undiscovered neighbour vv of uu, setting dist[v]=dist[u]+1\texttt{dist}[v] = \texttt{dist}[u] + 1 and the parent of vv to uu, and adds it at the tail. The parent links form the BFS tree, rooted at ss.

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 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 from ss, the discovered vertices are those reachable from ss, dist[v]=δ(s,v)\texttt{dist}[v] = \delta(s, v) for each, and the path of parents from vv up to ss, read backwards, is a shortest 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][s]; removing the head uu, of value kk, and appending vertices of value k+1k + 1 keeps it, since the other values were between kk and k+1k + 1. So vertices leave the queue by non-decreasing dist. Each dist[v]\texttt{dist}[v] is the length of the parent path, so dist[v]≥δ(s,v)\texttt{dist}[v] \geq \delta(s, v). Suppose some vv has dist[v]>δ(s,v)=k\texttt{dist}[v] > \delta(s, v) = k, with kk smallest; k≥1k \geq 1, and let uu be the vertex before vv on a shortest path, so dist[u]=δ(s,u)=k−1\texttt{dist}[u] = \delta(s, u) = k - 1. When uu left the queue, vv was discovered then, with value kk, or before, from a vertex that left the queue no later than uu, with value at most kk: a contradiction. Reachable vertices 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 .
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 Output 24.5.

Breadth-first search 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.

The same search two-colours a graph: colour ss with 0, and each newly discovered vertex with the colour its parent does not have. If an edge joins two vertices of the same colour, the graph is not bipartite, and the edge with the two tree paths up to the common ancestor of its ends is an odd cycle: the two paths have lengths of the same parity, since the colours of their ends agree.

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 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 is not bipartite: three people are friends with one another.

An odd cycle is a certificate: anyone can check in a moment that it is a cycle of the graph and that its length is odd, and no two-colouring survives it (Exercise 24.12).

24.5 Applications

Connected components. One search from an unmarked vertex marks exactly its component; restarting from each unmarked vertex in turn finds them all, in time O(n+m)O(n + m).

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 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 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.
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.

Topological order.

Definition 24.19 (Topological order)

A topological order of a directed graph is an order of its vertices in which, for every arc u→vu \to v, uu comes before vv.

A graph with a cycle has none: the first vertex of the cycle in the order would come after its predecessor on the cycle. A DAG has one, and depth-first search finds it.

Proposition 24.20 (Order by decreasing finishing time)

In a depth-first search of a DAG, f(v)<f(u)f(v) < f(u) for every arc u→vu \to v. So the vertices by decreasing finishing time are in topological order.

Proof. When u→vu \to v is examined, vv is not open: it would be an ancestor of uu and the arc a back edge, which a DAG does not have (Proposition 24.16). If vv is unmarked, it becomes a descendant of uu and finishes first (Theorem 24.15); if it is finished, it finished before uu, which is still open. ∎

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

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, by depth-first search 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.

Definition 24.21 (Component graph)

The component graph, or condensation, of a directed graph has its strongly connected components as vertices, and an arc C→C′C \to C' when some arc of the graph goes from CC to C′≠CC' \neq C.

The component graph is a DAG: a cycle through CC and C′C' would make their vertices reachable from one another, so C=C′C = C'. A search started in a component with no arc leaving it in the component graph 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 of GG and list the vertices by decreasing finishing time.
  2. Reverse every arc of GG.
  3. In the reversed graph, take the vertices in that list; from each one not yet assigned, search, and assign every vertex reached that is not yet assigned to a new component.
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 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. 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 CC and C′C' are distinct strongly connected components and some arc goes from CC to C′C', the largest finishing time in CC is larger than the largest in C′C'.

Proof. Let xx be the first vertex of C∪C′C \cup C' discovered. If x∈Cx \in C, every vertex of C∪C′C \cup C' is reachable from xx through unmarked vertices, so all are descendants of xx and finish before it. If x∈C′x \in C', no vertex of CC is reachable from xx (or CC and C′C' would merge), so all of C′C' finishes, as descendants of xx, before any vertex of CC is discovered. ∎

The proof that Kosaraju’s algorithm is correct is Exercise 24.10: the vertex with the largest finishing time lies in a component with no arc entering it, and in the reversed graph that component has no arc leaving it. Both searches cost O(n+m)O(n + m), and so does reversing the 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.
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.

Bridges.

Definition 24.24 (Bridge)

A bridge of an undirected graph is an edge whose removal increases the number of connected components.

An edge is a bridge exactly when it lies on no cycle: if uvuv is on a cycle, the rest of the cycle still joins uu and vv; if it is not, no other path joins them. In a depth-first search of an undirected graph there are no cross edges (an edge to a finished vertex not a descendant would have been taken from the earlier one), so every non-tree edge joins a vertex to an ancestor. Let low(v)\mathrm{low}(v) be the smallest discovery time reachable from the subtree of vv by going down tree edges and then along at most one other edge. A tree edge uvu v, with uu the parent, is on a cycle exactly when some edge leaves the subtree of vv for uu or above, that is when low(v)≤d(u)\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 of a connected undirected graph can be oriented so that the resulting directed graph is strongly connected if and only if the graph has no bridge.

Robbins proved it in 1939, in a paper whose title names its application, traffic control. The proof, the bridges and the orientation of Brenmoor’s roads are the weekend problem.

24.6 Exercises

Exercise 24.1 ★

A graph on the vertices 1 to 6 has the edges 12,13,23,24,35,45,5612, 13, 23, 24, 35, 45, 56. Give the degrees, check the handshake lemma, and list the vertices of odd degree.

Solution

Solution of Exercise 24.1.

deg⁡1=2\deg 1 = 2, deg⁡2=3\deg 2 = 3, deg⁡3=3\deg 3 = 3, deg⁡4=2\deg 4 = 2, deg⁡5=3\deg 5 = 3, deg⁡6=1\deg 6 = 1: the sum is 14=2×714 = 2 \times 7. The vertices of odd degree are 2, 3, 5 and 6: four of them, an even number.

Exercise 24.2 ★

Run dfs on the arcs 1→21 \to 2, 1→31 \to 3, 2→42 \to 4, 3→43 \to 4, 4→14 \to 1, 3→53 \to 5, 5→65 \to 6, 6→56 \to 5, added in this order. Give the times and the class of each arc.

Solution

Solution of Exercise 24.2.

Times d∣fd|f: 11: 1∣121|12, 22: 2∣52|5, 44: 3∣43|4, 33: 6∣116|11, 55: 7∣107|10, 66: 8∣98|9. Tree edges 1→21 \to 2, 2→42 \to 4, 1→31 \to 3, 3→53 \to 5, 5→65 \to 6; back edges 4→14 \to 1 and 6→56 \to 5; cross edge 3→43 \to 4 (4 is finished and was discovered before 3); no forward edge.

Exercise 24.3 ★

Give the distances from vertex 1 in the graph of Exercise 24.1, and a BFS tree.

Solution

Solution of Exercise 24.3.

δ(1,1)=0\delta(1, 1) = 0; δ(1,2)=δ(1,3)=1\delta(1, 2) = \delta(1, 3) = 1; δ(1,4)=δ(1,5)=2\delta(1, 4) = \delta(1, 5) = 2; δ(1,6)=3\delta(1, 6) = 3. With neighbours taken in increasing order, the BFS tree has the edges 12,13,24,35,5612, 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 by Kahn’s method and one by depth-first search.

Solution

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 gives, by decreasing finishing time, tin, chop, fry, sauce, boil, pasta, serve. Both put each task after the ones it needs.

Exercise 24.5 ★★

This search marks a vertex only when its visit ends. Explain the two lines of output; what happens on a graph with a cycle, and why does a DAG survive?

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 cycle. Some lines are left out.
Solution

Solution of Exercise 24.5.

A vertex is unmarked while it is open. On a DAG the search never meets an open vertex again (that would be a back edge), and a finished vertex is marked: each vertex is visited once, 31 visits for 31 vertices. On a cycle, the search comes back to an open vertex, which is not marked, and starts it again: xx, yy, xx, yy, …, until the call stack overflows. Marking on entry, as dfs does, fixes it.

Exercise 24.6 ★★

Find the graph this test misjudges, and repair it.

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 test code/bachelor-1/24-graph-traversals/listings/exo_bipartite_one.py
bipartite? True
Output 24.11. A path 1–2–3–4 and a triangle 5, 6, 7. Some lines are left out.
Solution

Solution of Exercise 24.6.

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

Exercise 24.7 ★★

Modify breadth-first search to count, for every vertex vv, the shortest paths from ss to vv, in time O(n+m)O(n + m).

Solution

Solution of Exercise 24.7.

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 code/bachelor-1/24-graph-traversals/exercises/count_paths.py

A shortest path to vv ends with an edge uvu v where δ(s,u)=δ(s,v)−1\delta(s, u) = \delta(s, v) - 1, and those paths are counted by the sum of the counts of such uu. Every such uu leaves the queue before vv 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 on random graphs.

Exercise 24.8 ★★

Write a function that returns a cycle of a directed graph, as a list of vertices, or None if the graph is acyclic, in time O(n+m)O(n + m).

Solution

Solution of Exercise 24.8.

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, from the first back edge code/bachelor-1/24-graph-traversals/exercises/find_cycle.py

By Proposition 24.16, a cycle exists exactly when the search meets a back edge u→vu \to v; the parents lead from uu up to vv, and reversed they give the cycle. The search is O(n+m)O(n + m), and the cycle is built once.

Exercise 24.9 ★★

Show that a free tree with nn vertices has n−1n - 1 edges, and that a connected graph with nn vertices and n−1n - 1 edges is a free tree.

Solution

Solution of Exercise 24.9.

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

Exercise 24.10 ★★★

Prove that Kosaraju’s algorithm finds the strongly connected components.

Solution

Solution of Exercise 24.10.

We show by induction that each search of the second pass assigns exactly one strongly connected component. Suppose the assigned vertices are a union of components, and the search starts from ss, the unassigned vertex with the largest finishing time, in the component CC. Reversing arcs keeps components, and none of CC is assigned, so the search reaches all of CC. Suppose it leaves CC: the first vertex reached outside CC, in a component C′C' not assigned, is reached by a reversed arc, that is, an arc of GG from C′C' to CC. By Lemma 24.23 some vertex of C′C' finishes after every vertex of CC, so after ss: impossible, since ss has the largest finishing time among the unassigned vertices. So the search assigns exactly CC, and the induction goes on.

Exercise 24.11 ★★★

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

Solution

Solution of Exercise 24.11.

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 is even, a walk that enters a vertex other than its start can leave it again: the walk gets stuck only at the vertex 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 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)O(n + m). The test builds graphs as unions of random closed walks, whose degrees are all even, and checks that the circuit uses each edge once.

Exercise 24.12 ★★★

Prove that an undirected graph is bipartite if and only if it has no cycle of odd length.

Solution

Solution of Exercise 24.12.

If GG is two-coloured, the colours alternate along a cycle, which returns to its first colour after an even number of steps. Conversely, suppose GG has no odd cycle, and colour each component by the parity of the distance from a vertex ss found by breadth-first search. If an edge uvu v joins two vertices of the same colour, let ww be the last common vertex of the tree paths from ss to uu and to vv. The tree paths from ww to uu and to vv share only ww, and their lengths δ(s,u)−δ(s,w)\delta(s, u) - \delta(s, w) and δ(s,v)−δ(s,w)\delta(s, v) - \delta(s, w) have the same parity; with uvu v they form a cycle 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 serves as a warm-up.

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 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 among friends, and among roads.
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 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.

Part I — The friendship graph.

  1. Using Output 24.1, how many friendships does person 40 have, and what is the average degree?
  2. Why does Output 24.7 count person 40 as a component?
  3. What do the components tell about the three groups of friends drawn in Section 24.5?
  4. Why does the triangle of Output 24.6 prove that the graph is not bipartite?
  5. Could two of the components be bipartite while the whole graph is not? What would the program print?
  6. What is the cost of the component and bipartite searches, in nn and mm?

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

  1. How many arcs would the road graph have if road 1 were two-way?
  2. Explain the single component of Output 24.9: which path leads from the Library back to the Town Square?
  3. Why does listing each road from its smaller place number make a DAG, and why does a DAG have only components of one vertex?
  4. In the component graph of the roads oriented as listed, which vertices have no incoming arc?
  5. What is the cost of Kosaraju’s algorithm on the roads?
  6. Why does reversing every arc leave the strongly connected components unchanged?

Part III — Bridges.

  1. Show that an edge is a bridge if and only if it lies on no cycle.
  2. Why does a depth-first search of an undirected graph have no cross edges?
  3. Prove that a tree edge uvu v, uu the parent, is a bridge if and only if low(v)>d(u)\mathrm{low}(v) > d(u).
  4. Why does visit skip the edge back to the parent, and only once?
  5. The friendship graph has 12 bridges: what do they say about the groups of friends?
  6. Why can the road graph have no bridge, given how its roads were laid (each place joined to its three nearest)? Is this a proof?

Part IV — Robbins’ theorem.

  1. Show that a graph with a bridge has no strongly connected orientation.
  2. In orient, why is every edge oriented exactly once?
  3. Show that in the orientation, every vertex is reachable from the root.
  4. Show that, if the graph has no bridge, the root is reachable from every vertex in the orientation.
  5. Deduce Robbins’ theorem.
  6. Why does road 1 keep the direction it has today?
  7. State the named result, Robbins’ theorem, and what the program checked on Brenmoor.
Solution

Solution of Problem 24.1.

1. None: the smallest degree is 0, and person 40 has it. The average degree is 100/40=2.5100 / 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 (11–2828 and 55–3737) 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 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 is bipartite exactly when all its components are. The program would print an odd cycle of the component that is not.

6. O(n+m)O(n + m): each vertex 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 but 1→31 \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 back to the Town Square.

9. Along any path the place numbers increase, so no path returns to its start: there is no cycle. Two distinct vertices that reach each other would make a cycle, so each component has one vertex.

10. The component graph is the DAG itself; the vertices without incoming arcs are the places never listed second: 1, 2, 4, 5, 6, 8 and 18.

11. O(n+m)O(n + m) with n=30n = 30 and m=105m = 105, for each of the two searches and for reversing the arcs.

12. A path from uu to vv in GG is, reversed, a path from vv to uu in the reversed graph; reaching each other is unchanged.

13. If uvu v lies on a cycle, the rest of the cycle joins uu and vv after removing it, and every path that used the edge can go around: the components stay the same. If uvu v lies on no cycle, any other path from uu to vv would close a cycle with it; so removing it separates uu from vv.

14. When an edge uvu v is first examined from uu, vv is either unmarked, and the edge becomes a tree edge, or open, an ancestor; if vv were finished, uvu v would already have been examined from vv, when uu was unmarked or open, so uu would be a descendant of vv.

15. With no cross edges, every edge leaving the subtree of vv other than uvu v goes to an ancestor of vv, so to uu or above, with a discovery time at most d(u)d(u). Such an edge exists exactly when low(v)≤d(u)\mathrm{low}(v) \leq d(u), and it closes a cycle through uvu v with tree paths. If none exists, every path from the subtree to the rest uses uvu v, which is a bridge.

16. The tree edge itself would give low(v)≤d(u)\mathrm{low}(v) \leq d(u) and hide every bridge. Only once, because a second edge between the same two vertices is a real cycle of two edges: 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; 1212–2020 holds people 20 and 18 to the rest, and 3333–3939 people 33 and 35. Inside the groups, no single friendship matters.

18. Joining each place to its three nearest makes cycles likely, but two clusters could still be joined by a single road: it is not a proof. The program checked: 0 bridges.

19. Let uvu v be a bridge, oriented u→vu \to v. Every path from the side of vv to the side of uu must use the edge, which points the other way: no orientation makes uu reachable from vv.

20. An edge is examined from both ends. A tree edge is added when the parent examines it; from the child, it is skipped, since the arc already exists. A non-tree edge joins a vertex 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 on that side of the test, or the arc already exists.

21. Tree edges point from parent to child, so the tree path from the root to any vertex is a directed path.

22. Let vv be a vertex other than the root, with parent pp. The edge pvp v is not a bridge, so by question 15 some edge goes from a vertex xx of the subtree of vv to a proper ancestor aa of vv. It is oriented upwards, x→ax \to a, and tree arcs lead from vv down to xx: aa is reachable from vv, and d(a)<d(v)d(a) < d(v). Repeating from aa, the discovery times decrease, so the walk ends at the root.

23. A bridge forbids a strongly connected orientation (question 19). Without a bridge, the orientation of orient lets every vertex reach the root and the root reach every vertex, so every vertex 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→31 \to 3 is a tree edge, oriented from parent to child.

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

Termos definidos neste capítulo

Ver todos os 1050 termos do glossário