TExcelTAD
Home › Graph Algorithms › Exercises

Exercises

Thirteen problems covering the whole course: searches, topological sort and components, spanning trees, single-source and all-pairs shortest paths, and flows. Try each one on paper first. Every problem has a short Answer to check yourself against and a full Solution; several solutions include a program that confirms the result, which you can edit and run.

Tip: Draw the graph. For searches, write the queue or the recursion stack next to it after every step; for shortest paths, write the current estimate on every vertex; for flows, write "flow/capacity" on every edge. Most mistakes in this material are a neighbour visited in the wrong order or a residual edge forgotten, and a drawing exposes both.

# Exercise Practises
1 Distances by hand BFS
2 Timestamps and edge kinds DFS, edge classification
3 How many schedules? topological sort, Kahn
4 One edge to connect them all strongly connected components
5 The bottleneck property MST, cut property
6 The second-best spanning tree MST, cycle property
7 Why not add a constant? Dijkstra, negative weights
8 What pass ii guarantees Bellman-Ford, relaxation
9 Solve or refute difference constraints
10 Potentials by hand Johnson's reweighting
11 Flow and cut max-flow min-cut
12 When Hall's condition fails bipartite matching
13 A cycle in O(V)O(V) time DFS, undirected graphs

Exercise 1: Distances by hand

Run BFS from AA on the undirected graph with edges AB,AC,BD,CD,CF,DE,EFAB, AC, BD, CD, CF, DE, EF (neighbours in alphabetical order). Give every distance and the parent of every vertex.

Answer

dd: A=0A = 0; B=C=1B = C = 1; D=F=2D = F = 2; E=3E = 3. Parents: B,C←AB, C \leftarrow A; D←BD \leftarrow B; F←CF \leftarrow C; E←DE \leftarrow D.

Solution

The queue evolves as [A][A], [B,C][B, C], [C,D][C, D], [D,F][D, F], [F,E][F, E], [E][E]. DD is discovered from BB, which leaves the queue before CC, and EE from DD, which leaves before FF; when FF is dequeued, EE is already discovered. See Breadth-First Search.

python · try it yourself
from collections import deque

adj = {}
for u, v in ["AB", "AC", "BD", "CD", "CF", "DE", "EF"]:
    adj.setdefault(u, []).append(v); adj.setdefault(v, []).append(u)
d, parent, q = {"A": 0}, {"A": None}, deque("A")
while q:
    u = q.popleft()
    for v in sorted(adj[u]):
        if v not in d:
            d[v], parent[v] = d[u] + 1, u
            q.append(v)
print(d)
print(parent)
{'A': 0, 'B': 1, 'C': 1, 'D': 2, 'F': 2, 'E': 3}
{'A': None, 'B': 'A', 'C': 'A', 'D': 'B', 'F': 'C', 'E': 'D'}

Exercise 2: Timestamps and edge kinds

Run DFS on the directed graph with edges A→BA \to B, B→CB \to C, C→AC \to A, A→DA \to D, D→CD \to C, starting at AA, neighbours in alphabetical order. Give every interval [d,f][d, f] and classify every edge.

Answer

A[1,8]A [1, 8], B[2,5]B [2, 5], C[3,4]C [3, 4], D[6,7]D [6, 7]. Tree edges ABAB, BCBC, ADAD; back edge CACA; cross edge DCDC.

Solution

From AA the search goes to BB (time 2), then CC (time 3). C→AC \to A finds AA gray: a back edge. CC finishes at 4 and BB at 5. Back at AA, DD is discovered at 6; D→CD \to C finds CC black with C.d=3<D.d=6C.d = 3 < D.d = 6: a cross edge. DD finishes at 7 and AA at 8. The back edge shows the cycle A→B→C→AA \to B \to C \to A, as the white-path argument predicts. Rules in Classifying the Edges of a DFS.

Exercise 3: How many schedules?

A DAG has edges A→CA \to C, B→CB \to C, C→DC \to D, C→EC \to E. How many topological orders does it have, and which one does Kahn's algorithm with a min-heap return?

Answer

4 orders. Kahn's algorithm returns A,B,C,D,EA, B, C, D, E.

Solution

CC must come after both AA and BB and before both DD and EE. So every order is (an order of A,BA, B), CC, (an order of D,ED, E): 2⋅1⋅2=42 \cdot 1 \cdot 2 = 4. The min-heap always takes the smallest ready name: AA and BB are ready first, AA wins, then BB, then CC, then DD before EE. See Kahn's Algorithm.

Exercise 4: One edge to connect them all

A directed graph has edges A→BA \to B, B→CB \to C, C→AC \to A, C→DC \to D, D→ED \to E, E→DE \to D, E→FE \to F. Find its strongly connected components and its component graph. Which single new edge makes the whole graph strongly connected?

Answer

Components {A,B,C}\{A, B, C\}, {D,E}\{D, E\}, {F}\{F\}, with component graph C1→C2→C3C_1 \to C_2 \to C_3. Adding any edge from FF to a vertex of {A,B,C}\{A, B, C\}, for example F→AF \to A, makes it strongly connected.

Solution

The component graph is a path, a DAG with one source C1C_1 and one sink C3C_3. An edge from the sink component to the source component closes a cycle through all three components, merging them. In general, if the component graph has aa sources and bb sinks (and more than one component), at least max⁡(a,b)\max(a, b) new edges are needed, since every source needs a new entering edge and every sink a new leaving one; here max⁡(1,1)=1\max(1, 1) = 1. The program checks the claim with Kosaraju's algorithm.

python · try it yourself
def scc_count(adj):
    seen, order = set(), []
    def v1(u):
        seen.add(u)
        for w in adj.get(u, []):
            if w not in seen: v1(w)
        order.append(u)
    for u in sorted(adj):
        if u not in seen: v1(u)
    radj = {}
    for u in adj:
        for w in adj[u]:
            radj.setdefault(w, []).append(u)
    comp, count = {}, 0
    def v2(u):
        comp[u] = count
        for w in radj.get(u, []):
            if w not in comp: v2(w)
    for u in reversed(order):
        if u not in comp:
            v2(u); count += 1
    return count

g = {"A": ["B"], "B": ["C"], "C": ["A", "D"], "D": ["E"], "E": ["D", "F"], "F": []}
print("components:", scc_count(g))
g["F"] = ["A"]
print("after adding F -> A:", scc_count(g))
components: 3
after adding F -> A: 1

Exercise 5: The bottleneck property

Prove that a minimum spanning tree TT also minimizes the largest edge weight among all spanning trees: no spanning tree has a smaller maximum edge.

Answer

If a spanning tree T′T' had all edges lighter than the heaviest edge ee of TT, then removing ee from TT defines a cut that T′T' must cross with some edge e′e', and w(e′)<w(e)w(e') < w(e); swapping ee for e′e' would give a lighter spanning tree than TT.

Solution

Let ee be a heaviest edge of the MST TT, and suppose a spanning tree T′T' has maximum edge weight smaller than w(e)w(e). Removing ee splits TT into two components, which define a cut (S,V∖S)(S, V \setminus S). T′T' is connected, so some edge e′∈T′e' \in T' crosses this cut, and w(e′)<w(e)w(e') < w(e) by assumption. Then T∖{e}∪{e′}T \setminus \{e\} \cup \{e'\} is a spanning tree (the two components are reconnected) of weight w(T)−w(e)+w(e′)<w(T)w(T) - w(e) + w(e') < w(T), contradicting minimality. The converse is false: a bottleneck spanning tree need not be minimum. This is the exchange argument of the cut property.

Exercise 6: The second-best spanning tree

For the graph of Kruskal's algorithm (edges AB:4AB{:}4, AC:3AC{:}3, BC:2BC{:}2, BD:5BD{:}5, CE:7CE{:}7, DE:6DE{:}6, DF:9DF{:}9, EG:8EG{:}8, FG:10FG{:}10, FH:1FH{:}1, GH:11GH{:}11, EF:12EF{:}12), find the weight of the lightest spanning tree that differs from the MST.

Answer
  1. The MST weighs 34, and three different swaps cost only 1 more: add AB:4AB{:}4 and remove AC:3AC{:}3, add CE:7CE{:}7 and remove DE:6DE{:}6, or add FG:10FG{:}10 and remove DF:9DF{:}9.
Solution

A second-best spanning tree differs from the MST by a single swap: add one non-tree edge (u,v)(u, v), which closes a cycle with the tree path from uu to vv, and remove the heaviest tree edge on that path. Trying every non-tree edge, with the path-maximum check, gives the best swap. The program does it with a plain search per candidate.

python · try it yourself
edges = [("A", "B", 4), ("A", "C", 3), ("B", "C", 2), ("B", "D", 5), ("C", "E", 7), ("D", "E", 6),
         ("D", "F", 9), ("E", "G", 8), ("F", "G", 10), ("F", "H", 1), ("G", "H", 11), ("E", "F", 12)]
parent = {v: v for v in "ABCDEFGH"}
def find(x):
    while parent[x] != x:
        x = parent[x]
    return x
mst = []
for u, v, w in sorted(edges, key=lambda e: e[2]):
    if find(u) != find(v):
        parent[find(u)] = find(v); mst.append((u, v, w))
base = sum(w for *_, w in mst)

def heaviest_on_path(tree, u, v):
    adj = {}
    for a, b, w in tree:
        adj.setdefault(a, []).append((b, w)); adj.setdefault(b, []).append((a, w))
    best, stack = {u: (0, None)}, [u]
    while stack:
        x = stack.pop()
        for y, w in adj[x]:
            if y not in best:
                best[y] = max(best[x], (w, (x, y))); stack.append(y)
    return best[v]

options = []
for u, v, w in edges:
    if (u, v, w) not in mst:
        heavy, e = heaviest_on_path(mst, u, v)
        options.append((base + w - heavy, f"add {u}{v}:{w}, remove {e[0]}{e[1]}:{heavy}"))
print("MST weight", base)
for cost, how in sorted(options)[:3]:
    print(cost, how)
MST weight 34
35 add AB:4, remove AC:3
35 add CE:7, remove DE:6
35 add FG:10, remove FD:9

Exercise 7: Why not add a constant?

Give a graph with one negative edge where adding the same constant to every weight (to make them non-negative) changes which path is shortest.

Answer

Edges A→B:3A \to B{:}3, B→C:−3B \to C{:}-3, A→C:1A \to C{:}1. The shortest path from AA to CC is A→B→CA \to B \to C (weight 0). Adding 3 to every edge gives weights 6, 0 and 4, and now A→CA \to C (4) beats A→B→CA \to B \to C (6).

Solution

Adding cc to every edge adds kckc to a path with kk edges, so it penalizes paths with more edges, and the two-edge path loses to the one-edge path. Johnson's reweighting adds h(u)−h(v)h(u) - h(v) instead, which shifts all paths between the same two vertices by the same amount. With h=δ(s,⋅)h = \delta(s, \cdot) from an added source, h=(0,0,−3)h = (0, 0, -3) for (A,B,C)(A, B, C), and the new weights are 33, 00 and 44: A→B→CA \to B \to C (3) still wins.

Exercise 8: What pass ii guarantees

Prove that after pass ii of Bellman-Ford, v.dv.d is at most the weight of every path from ss to vv with at most ii edges, whatever order the edges are relaxed in.

Answer

Induction on ii: a path with at most ii edges is a path with at most i−1i - 1 edges to some uu plus an edge (u,v)(u, v), which pass ii relaxes after u.du.d has already reached the required bound.

Solution

For i=0i = 0, the only path with 0 edges is from ss to ss, and s.d=0s.d = 0. Assume the claim after pass i−1i - 1, and let pp be a path to vv with at most ii edges. If it has fewer than ii edges, the claim holds already, since estimates never increase. Otherwise pp is a path p′p' to some uu with i−1i - 1 edges, followed by (u,v)(u, v). After pass i−1i - 1, u.d≤w(p′)u.d \le w(p'), and during pass ii the edge (u,v)(u, v) is relaxed, so afterwards v.d≤u.d+w(u,v)≤w(p′)+w(u,v)=w(p)v.d \le u.d + w(u, v) \le w(p') + w(u, v) = w(p). The claim gives the correctness of Bellman-Ford directly: some shortest path has at most V−1V - 1 edges, and v.dv.d never drops below δ(s,v)\delta(s, v) (upper-bound property).

Exercise 9: Solve or refute

Find a solution of the system x1−x2≤3x_1 - x_2 \le 3, x2−x3≤−2x_2 - x_3 \le -2, x3−x1≤1x_3 - x_1 \le 1, x1−x3≤0x_1 - x_3 \le 0, x4−x1≤−1x_4 - x_1 \le -1, x4−x3≤2x_4 - x_3 \le 2. Then add x3−x2≤1x_3 - x_2 \le 1 and show that the new system has no solution.

Answer

x=(0,−2,0,−1)x = (0, -2, 0, -1) (or any shift of it). With x3−x2≤1x_3 - x_2 \le 1 added, the constraints x2−x3≤−2x_2 - x_3 \le -2 and x3−x2≤1x_3 - x_2 \le 1 add up to 0≤−10 \le -1.

Solution

Build the constraint graph: an edge (vi,vj)(v_i, v_j) of weight bb for each xj−xi≤bx_j - x_i \le b, and start every estimate at 0. Bellman-Ford converges to (0,−2,0,−1)(0, -2, 0, -1). In the second system the edges v3→v2v_3 \to v_2 (weight −2-2) and v2→v3v_2 \to v_3 (weight 1) form a cycle of weight −1-1.

python · try it yourself
def solve(n, cons):                                     # cons: (j, i, b) means x_j - x_i <= b
    x = [0] * (n + 1)
    for _ in range(n):
        for j, i, b in cons:
            x[j] = min(x[j], x[i] + b)
    ok = all(x[j] - x[i] <= b for j, i, b in cons)
    return x[1:] if ok else "no solution (negative cycle)"

system = [(1, 2, 3), (2, 3, -2), (3, 1, 1), (1, 3, 0), (4, 1, -1), (4, 3, 2)]
print(solve(4, system))
print(solve(4, system + [(3, 2, 1)]))
[0, -2, 0, -1]
no solution (negative cycle)

Exercise 10: Potentials by hand

A directed graph has edges A→B:2A \to B{:}2, B→C:−4B \to C{:}-4, A→C:1A \to C{:}1, C→D:3C \to D{:}3, B→D:−1B \to D{:}-1. Compute Johnson's potentials hh and all reweighted edges.

Answer

h=(0,0,−4,−1)h = (0, 0, -4, -1) for A,B,C,DA, B, C, D. New weights: AB:2AB{:}2, BC:0BC{:}0, AC:5AC{:}5, CD:0CD{:}0, BD:0BD{:}0.

Solution

With every estimate starting at 0 (the edges from the added source), Bellman-Ford gives h(A)=0h(A) = 0, h(B)=0h(B) = 0 (nothing negative enters BB), h(C)=−4h(C) = -4 (through B→CB \to C) and h(D)=min⁡(0,h(C)+3,h(B)−1)=−1h(D) = \min(0, h(C) + 3, h(B) - 1) = -1. Then w^(u,v)=w(u,v)+h(u)−h(v)\hat{w}(u, v) = w(u, v) + h(u) - h(v): for example w^(A,C)=1+0+4=5\hat{w}(A, C) = 1 + 0 + 4 = 5. Every new weight is ≥0\ge 0, and the edges on shortest paths from the added source become 0. See Johnson's Algorithm and Reweighting.

python · try it yourself
edges = [("A", "B", 2), ("B", "C", -4), ("A", "C", 1), ("C", "D", 3), ("B", "D", -1)]
h = {v: 0 for v in "ABCD"}
for _ in range(4):
    for u, v, w in edges:
        h[v] = min(h[v], h[u] + w)
print("h:", h)
print("new weights:", ", ".join(f"{u}{v}:{w + h[u] - h[v]}" for u, v, w in edges))
h: {'A': 0, 'B': 0, 'C': -4, 'D': -1}
new weights: AB:2, BC:0, AC:5, CD:0, BD:0

Exercise 11: Flow and cut

Find a maximum flow and a minimum cut of the network with capacities S→A:5S \to A{:}5, S→B:4S \to B{:}4, A→B:2A \to B{:}2, A→C:3A \to C{:}3, B→D:5B \to D{:}5, C→T:4C \to T{:}4, D→C:2D \to C{:}2, D→T:3D \to T{:}3.

Answer

Maximum flow 7; the minimum cut is the two edges into TT, C→TC \to T and D→TD \to T, of capacity 4+3=74 + 3 = 7.

Solution

Augment, for example, S→A→C→TS \to A \to C \to T by 3, S→B→D→TS \to B \to D \to T by 3, and S→B→D→C→TS \to B \to D \to C \to T by 1: value 7. The edges into TT have total capacity 7, so no flow can do better, and by the max-flow min-cut theorem both are optimal. The program confirms it with Edmonds-Karp and reads off the residual cut.

python · try it yourself
from collections import deque

cap = {("S", "A"): 5, ("S", "B"): 4, ("A", "B"): 2, ("A", "C"): 3, ("B", "D"): 5,
       ("C", "T"): 4, ("D", "C"): 2, ("D", "T"): 3}
flow = dict.fromkeys(cap, 0)
def bfs():
    prev, q = {"S": None}, deque("S")
    while q:
        u = q.popleft()
        for (a, b), c in cap.items():
            if a == u and flow[(a, b)] < c and b not in prev:
                prev[b] = (a, b, 1); q.append(b)
            if b == u and flow[(a, b)] > 0 and a not in prev:
                prev[a] = (a, b, -1); q.append(a)
    return prev
value = 0
while "T" in (prev := bfs()):
    steps, v = [], "T"
    while prev[v]:
        a, b, sign = prev[v]; steps.append((a, b, sign)); v = a if sign == 1 else b
    bottleneck = min(cap[(a, b)] - flow[(a, b)] if s == 1 else flow[(a, b)] for a, b, s in steps)
    for a, b, s in steps:
        flow[(a, b)] += s * bottleneck
    value += bottleneck
S = set(bfs())
print("maximum flow", value)
print("cut S-side", sorted(S), "edges", [f"{a}{b}" for (a, b) in cap if a in S and b not in S])
maximum flow 7
cut S-side ['A', 'B', 'C', 'D', 'S'] edges ['CT', 'DT']

Exercise 12: When Hall's condition fails

Workers P,Q,R,UP, Q, R, U and machines 1,2,3,41, 2, 3, 4: PP and QQ can only run machine 1, RR can run 1 or 2, UU can run 3 or 4. What is the size of a maximum matching, and which set of workers shows that no perfect matching exists?

Answer

3, for example PP-1, RR-2, UU-3. The set {P,Q}\{P, Q\} has only one machine among its neighbours.

Solution

Hall's theorem (Discrete Mathematics) says a matching saturating all workers exists if and only if every set XX of workers has at least ∣X∣\lvert X \rvert neighbours. {P,Q}\{P, Q\} has the single neighbour {1}\{1\}, so one of P,QP, Q stays unmatched, and the maximum is at most 3. The matching above has 3 edges. In flow terms, the minimum cut has capacity 3; see Maximum Bipartite Matching.

Exercise 13: A cycle in O(V)O(V) time

Show how to decide whether an undirected graph given by adjacency lists has a cycle in O(V)O(V) time, independent of EE.

Answer

Run DFS and stop at the first back edge. Before it finds one, every edge examined is a tree edge (or the edge back to the parent), and a forest has at most V−1V - 1 edges, so at most O(V)O(V) list entries are examined.

Solution

In an undirected DFS every edge is a tree edge or a back edge. While no back edge has appeared, the explored edges form a forest, which has fewer than VV edges; each is seen at most twice (once from each end, the second time as the edge to the parent, which is skipped). The first entry that is neither leads to an already discovered vertex: a back edge, so a cycle, and the search stops. Hence at most 2(V−1)+12(V - 1) + 1 list entries are examined before the answer is known, plus O(V)O(V) for the outer loop. The same argument shows that a graph with E≥VE \ge V always has a cycle.

Test yourself

Which algorithm finds shortest paths in a DAG with negative edge weights in linear time?

  1. Dijkstra
  2. Relaxing edges in topological order
  3. Prim
  4. BFS

You need all-pairs shortest paths on a sparse graph with negative edges and no negative cycles. Which algorithm is asymptotically best?

  1. Floyd-Warshall, Θ(V3)\Theta(V^3)
  2. Johnson's algorithm, O(VElg⁡V)O(VE \lg V)
  3. Repeated squaring, Θ(V3lg⁡V)\Theta(V^3 \lg V)
  4. VV runs of Dijkstra on the original weights

A maximum flow has value 12. What is the capacity of a minimum cut?

  1. At least 13
  2. Exactly 12
  3. At most 11
  4. It depends on the algorithm