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 is a finite set of vertices and a set of edges. In an undirected graph an edge is a set of two vertices, its ends, written . In a directed graph an edge is a pair , an arc from to , written . An edge whose two ends are equal is a loop; unless stated otherwise, graphs here have no loops and , .
Definition 24.2 (Degree)
The degree of a vertex of an undirected graph is the number of edges at ; its neighbours are the other ends of these edges. In a directed graph, the out-degree of counts the arcs leaving , its in-degree those arriving at .
Proposition 24.3 (Handshake lemma)
In an undirected graph, ; so the number of vertices of odd degree is even. In a directed graph, the out-degrees and the in-degrees both sum to .
Proof. Each edge is counted twice in the sum, once in and once in ; 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 from to is a sequence of vertices where each is an edge (an arc 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. is reachable from if there is a path from to .
Definition 24.5 (Distance)
The distance is the smallest length of a path from to , counted in edges, and if is not reachable from .
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, and 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 with vertices, the following are equivalent: (i) is a free tree; (ii) any two vertices are joined by exactly one simple path; (iii) is connected and has edges.
Proof. (i)(ii): a simple path exists, since is connected and a shortest path is simple. If two different simple paths join and , follow them from to the first vertex where they part, , and on the first one to the first vertex after that the second one also visits, ; the two pieces from to share only their ends and make a cycle. (ii)(i): is connected, and a cycle through would give two simple paths from to , the edge and the rest of the cycle. (i)(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 table whose entry is 1 when 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
$ 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
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 matrix | adjacency lists | edge list | |
|---|---|---|---|
| space | |||
| is an edge? | |||
| the neighbours of | |||
| add an edge |
$ python representations.py
graph n m matrix cells list entries edge list
roads 30 105 900 135 210
friendships 40 50 1600 140 100
A graph is sparse when is much smaller than , 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 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
$ python edge_file.py
106 lines; first two edges: '1 3', '1 23'
read back: same vertices and arcs: True
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 by marking it, then visiting in turn each unmarked neighbour of ; on the whole graph, it visits each vertex not yet marked. A clock ticks at each start and each end of a visit: ’s discovery time is the tick when its visit starts, its finishing time the tick when it ends. Between the two, is open. If the visit of calls the visit of , is the parent of ; the parent links form the DFS forest.
Definition 24.14 (Classes of arcs)
In a depth-first search of a directed graph, an arc is a tree edge if is the parent of ; a back edge if is an ancestor of in the forest, or itself; a forward edge if is a descendant of 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
When the arc is examined, 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 exactly when it was discovered after .
$ 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
a, then at e; each vertex carries . The tree edges form two trees, rooted at a and e.Theorem 24.15 (Parenthesis theorem)
For any two vertices and of a depth-first search, the intervals and are disjoint or one contains the other; and exactly when is a descendant of , .
Proof. Say . If is discovered while is open, ’s visit is called, directly or not, from ’s, so is a descendant of ; and a call returns before its caller does, so : nested. Otherwise finished before : disjoint. Conversely, a descendant of is discovered during ’s visit, so its interval is nested in ’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 is discovered, every vertex reachable from by a path of unmarked vertices becomes a descendant of (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 , with an ancestor of , closes a cycle with the tree path from to . Conversely, let be a cycle and its first vertex to be discovered, and the arc of that enters . At the rest of is unmarked, so becomes a descendant of by the white-path property, and 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
24.4 Breadth-first search
Definition 24.17 (Breadth-first search, BFS tree)
A breadth-first search from keeps a queue of discovered vertices, initially ; it removes the vertex at the head and discovers each undiscovered neighbour of , setting and the parent of to , and adds it at the tail. The parent links form the BFS tree, rooted at .
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
Theorem 24.18 (Breadth-first search computes distances)
At the end of a breadth-first search from , the discovered vertices are those reachable from , for each, and the path of parents from up to , 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 ; removing the head , of value , and appending vertices of value keeps it, since the other values were between and . So vertices leave the queue by non-decreasing dist. Each is the length of the parent path, so . Suppose some has , with smallest; , and let be the vertex before on a shortest path, so . When left the queue, was discovered then, with value , or before, from a vertex that left the queue no later than , with value at most : a contradiction. Reachable vertices are discovered by the same argument, with 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
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 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]
$ python bipartite.py
not bipartite: odd cycle of length 3: 5 - 1 - 12
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 .
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
$ 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]
figures/town_graphs.py: people 1–14, 15–27 and 28–39 on three circles, person 40 apart; the bridges are thick.Definition 24.19 (Topological order)
A topological order of a directed graph is an order of its vertices in which, for every arc , comes before .
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, for every arc . So the vertices by decreasing finishing time are in topological order.
Proof. When is examined, is not open: it would be an ancestor of and the arc a back edge, which a DAG does not have (Proposition 24.16). If is unmarked, it becomes a descendant of and finishes first (Theorem 24.15); if it is finished, it finished before , 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 ; 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
$ 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
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 when some arc of the graph goes from to .
The component graph is a DAG: a cycle through and would make their vertices reachable from one another, so . 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)
- Run a depth-first search of and list the vertices by decreasing finishing time.
- Reverse every arc of .
- 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
$ 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
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 and are distinct strongly connected components and some arc goes from to , the largest finishing time in is larger than the largest in .
Proof. Let be the first vertex of discovered. If , every vertex of is reachable from through unmarked vertices, so all are descendants of and finish before it. If , no vertex of is reachable from (or and would merge), so all of finishes, as descendants of , before any vertex of 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 , and so does reversing the graph.
abc, which no arc enters: reversed, no arc leaves it, so the search stays inside.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 is on a cycle, the rest of the cycle still joins and ; 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 be the smallest discovery time reachable from the subtree of by going down tree edges and then along at most one other edge. A tree edge , with the parent, is on a cycle exactly when some edge leaves the subtree of for or above, that is when . 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 . Give the degrees, check the handshake lemma, and list the vertices of odd degree.
Exercise 24.2 ★
Run dfs on the arcs , , , , , , , , added in this order. Give the times and the class of each arc.
Solution
Solution of Exercise 24.2.
Times : : , : , : , : , : , : . Tree edges , , , , ; back edges and ; cross edge (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.
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
10 diamonds, no cycle: 31 vertices, 31 visits
a cycle x -> y -> x: RecursionError
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: , , , , …, 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
bipartite? True
Exercise 24.7 ★★
Modify breadth-first search to count, for every vertex , the shortest paths from to , in time .
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
A shortest path to ends with an edge where , and those paths are counted by the sum of the counts of such . Every such leaves the queue before 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 .
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
By Proposition 24.16, a cycle exists exactly when the search meets a back edge ; the parents lead from up to , and reversed they give the cycle. The search is , and the cycle is built once.
Exercise 24.9 ★★
Show that a free tree with vertices has edges, and that a connected graph with vertices and edges is a free tree.
Solution
Solution of Exercise 24.9.
By induction on ; true for . A free tree with vertices has a vertex of degree 1: the end 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 and its edge leaves a free tree on vertices, with edges by induction: in all. Conversely, take a connected graph with vertices and edges; while it has a cycle, remove an edge of a cycle, which keeps it connected. The result is a free tree, with 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 , the unassigned vertex with the largest finishing time, in the component . Reversing arcs keeps components, and none of is assigned, so the search reaches all of . Suppose it leaves : the first vertex reached outside , in a component not assigned, is reached by a reversed arc, that is, an arc of from to . By Lemma 24.23 some vertex of finishes after every vertex of , so after : impossible, since has the largest finishing time among the unassigned vertices. So the search assigns exactly , 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 , 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]
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: . 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 is two-coloured, the colours alternate along a cycle, which returns to its first colour after an even number of steps. Conversely, suppose has no odd cycle, and colour each component by the parity of the distance from a vertex found by breadth-first search. If an edge joins two vertices of the same colour, let be the last common vertex of the tree paths from to and to . The tree paths from to and to share only , and their lengths and have the same parity; with 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
$ 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)
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
$ python orient.py
53 one-way roads for 53 roads; strongly connected components: 1
road 1 goes from 1 to 3, as now
Part I — The friendship graph.
- Using Output 24.1, how many friendships does person 40 have, and what is the average degree?
- Why does Output 24.7 count person 40 as a component?
- What do the components tell about the three groups of friends drawn in Section 24.5?
- Why does the triangle of Output 24.6 prove that the graph is not bipartite?
- Could two of the components be bipartite while the whole graph is not? What would the program print?
- What is the cost of the component and bipartite searches, in and ?
Part II — The roads and the one-way street.
- How many arcs would the road graph have if road 1 were two-way?
- Explain the single component of Output 24.9: which path leads from the Library back to the Town Square?
- Why does listing each road from its smaller place number make a DAG, and why does a DAG have only components of one vertex?
- In the component graph of the roads oriented as listed, which vertices have no incoming arc?
- What is the cost of Kosaraju’s algorithm on the roads?
- Why does reversing every arc leave the strongly connected components unchanged?
Part III — Bridges.
- Show that an edge is a bridge if and only if it lies on no cycle.
- Why does a depth-first search of an undirected graph have no cross edges?
- Prove that a tree edge , the parent, is a bridge if and only if .
- Why does
visitskip the edge back to the parent, and only once? - The friendship graph has 12 bridges: what do they say about the groups of friends?
- 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.
- Show that a graph with a bridge has no strongly connected orientation.
- In
orient, why is every edge oriented exactly once? - Show that in the orientation, every vertex is reachable from the root.
- Show that, if the graph has no bridge, the root is reachable from every vertex in the orientation.
- Deduce Robbins’ theorem.
- Why does road 1 keep the direction it has today?
- 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 .
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 (– and –) 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. : 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 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. with and , for each of the two searches and for reversing the arcs.
12. A path from to in is, reversed, a path from to in the reversed graph; reaching each other is unchanged.
13. If lies on a cycle, the rest of the cycle joins and after removing it, and every path that used the edge can go around: the components stay the same. If lies on no cycle, any other path from to would close a cycle with it; so removing it separates from .
14. When an edge is first examined from , is either unmarked, and the edge becomes a tree edge, or open, an ancestor; if were finished, would already have been examined from , when was unmarked or open, so would be a descendant of .
15. With no cross edges, every edge leaving the subtree of other than goes to an ancestor of , so to or above, with a discovery time at most . Such an edge exists exactly when , and it closes a cycle through with tree paths. If none exists, every path from the subtree to the rest uses , which is a bridge.
16. The tree edge itself would give 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; – holds people 20 and 18 to the rest, and – 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 be a bridge, oriented . Every path from the side of to the side of must use the edge, which points the other way: no orientation makes reachable from .
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 be a vertex other than the root, with parent . The edge is not a bridge, so by question 15 some edge goes from a vertex of the subtree of to a proper ancestor of . It is oriented upwards, , and tree arcs lead from down to : is reachable from , and . Repeating from , 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: 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
- Adjacency list, edge list
- Bipartite graph
- Breadth-first search, BFS tree
- Bridge
- Classes of arcs
- Component graph
- Connected, strongly connected
- Degree
- Depth-first search, discovery and finishing times
- Directed acyclic graph
- Distance
- Free tree, forest
- Graph, vertex, edge, arc, loop
- Path, simple path, cycle
- Topological order
- Weighted graph, labelled graph