3.5.7 · D4Graphs

Exercises — Topological sort — DFS-based, Kahn's algorithm (BFS-based)

2,388 words11 min readBack to topic

We reuse one running graph throughout so the figures stay familiar.

Figure — Topological sort — DFS-based, Kahn's algorithm (BFS-based)

Level 1 — Recognition

Exercise 1.1

Which of these directed graphs can be topologically sorted?

  • (a)
  • (b)
  • (c) a single vertex with no edges.
Recall Solution 1.1

A topological order exists if and only if the graph is a DAG (no directed cycle).

  • (a) is a cycle → no ordering. Following the arrows brings you back to , forcing before .
  • (b) No cycle. Valid order: . Yes.
  • (c) One vertex, no edges, trivially a DAG. Order is just . Yes.

Answer: (b) and (c).

Exercise 1.2

In Kahn's algorithm, which vertices of the running graph form the starting set (the initial queue)?

Recall Solution 1.2

The starting set is all vertices with indegree 0 — no arrows point into them, so they have no unmet prerequisites. Indegrees: . Answer: . (Look at the red vertices in the figure above — they have no incoming arrows.)


Level 2 — Application

Exercise 2.1

Run Kahn's algorithm on the running graph . When there is a tie (several indegree-0 vertices), always pop the smallest-numbered vertex. Give the full step table and the final order.

Recall Solution 2.1

We keep a queue of indegree-0 vertices. Pop the smallest, emit it, and decrement each neighbour's indegree; if a neighbour hits 0, push it.

Step Queue (indeg 0) Pop Emit Decrements New zeros
1 [4, 5] 4 4 ,
2 [5] 5 5 , 0, 2
3 [0, 2] 0 0
4 [2] 2 2 3
5 [3] 3 3 1
6 [1] 1 1

Order: . Emitted count , so is a valid DAG.

Exercise 2.2

Run the DFS-based algorithm starting the outer loop at vertex , then (visit neighbours in increasing order). Record vertices on finish, then reverse.

Recall Solution 2.2

We append each vertex only after every vertex reachable from it has finished, then reverse.

  • dfs(5): go to has no unvisited out-edges → finish 0. Back at , go to finish 1, finish 3, finish 2, finish 5.
  • dfs(4): neighbours already done → finish 4.
  • Finish list (in order of finishing): .
  • Reverse .

Note this differs from the Kahn order in 2.1 — both are valid, because the ordering is not unique.


Level 3 — Analysis

Exercise 3.1

For the running graph, how many distinct valid topological orders exist? Show the reasoning, not just a count.

Recall Solution 3.1

An order is valid iff it respects every "before" constraint. Constraints from the edges: Think of building the sequence left-to-right by repeatedly choosing any current indegree-0 vertex (exactly Kahn's freedom). We count all such choice-trees.

Track available sets step by step:

  • Start: available → 2 choices.

Rather than a messy tree, count by a cleaner argument. The "must-before" relations chain as and , plus and . Vertex only needs done; vertex needs and done.

Enumerate by hand (systematic): the linear extensions are

· · · · · · · · ·

Counting these gives 13 distinct valid orders.

Answer: 13. The point: multiplicity comes from independent roots ( and ) and from being free to slide anywhere after both .

Exercise 3.2

In the running graph, at which exact moment during Kahn's run does vertex become available (indegree hits 0)? Explain why it can then be placed anywhere until it is popped.

Recall Solution 3.2

's prerequisites are and (edges , ), so . It reaches 0 only after both and are emitted — that is step 2 in the table of 2.1. Once available, has no outgoing edges, so placing it does not create or block any new zero. Therefore it can be emitted at any later step without violating a constraint — this freedom is exactly why multiple valid orders exist.


Level 4 — Synthesis

Exercise 4.1 (Course Schedule)

You must take 4 courses. Prerequisites (edge = " before "): Can you finish all courses? If yes give an order; if no, explain. (This is the Course Schedule Problem pattern.)

Recall Solution 4.1

Follow the arrows: is a directed cycle. Kahn confirms it: Indegrees: . Start queue .

  • Pop , emit , decrement (). No new zero.
  • Queue empty. Emitted count . Fewer than emitted ⇒ a cycle remains among . Answer: No — the courses cannot all be finished; form a prerequisite loop.

Exercise 4.2 (Shortest Path in a DAG)

Using the running graph with every edge weight , compute the shortest distance from vertex to every reachable vertex by relaxing edges in the topological order . (Background: Shortest Path in DAG.)

Recall Solution 4.2

Initialise , all others . Relaxing an edge means: if , set . Process vertices in topo order so every is finalised before its edges are used.

  • Process (dist 0): edges , , .
  • Process (dist , unreachable from 4): skip its edges (relaxing from does nothing).
  • Process (dist 1): no out-edges.
  • Process (dist ): skip.
  • Process (dist ): skip.
  • Process (dist 1): no out-edges.

Distances from 4: ; vertices are unreachable (). Why topo order works: when we finalise , all paths into came from earlier (already-finalised) vertices, so is already correct.


Level 5 — Mastery

Exercise 5.1 (Prove the DFS property)

Prove: for a DAG, in a DFS every edge satisfies , where is the finish time. (This is the correctness core of Depth-First Search (DFS)-based topo sort.)

Recall Solution 5.1

Consider the moment DFS first discovers (colours it gray). Look at 's colour, three exhaustive cases:

  1. white (undiscovered): DFS will recurse into from (directly or via other white descendants), so becomes a descendant of in the DFS tree. Descendants finish before their ancestor pops, hence . ✅
  2. black (already finished): then finished before we even started , so . ✅
  3. gray (on the stack): gray means there is an active path . Together with edge this closes a directed cycle — impossible in a DAG. So this case never occurs.

In cases 1 and 2 (the only ones possible), . Therefore sorting vertices by decreasing finish time places before for every edge.

Exercise 5.2 (Kahn always starts)

Prove: every non-empty DAG has at least one vertex with indegree 0, so Kahn's algorithm can always begin (and, by induction, always finishes).

Recall Solution 5.2

Suppose, for contradiction, every vertex has indegree . Pick any vertex ; it has an incoming edge from some . But also has indegree , so it has an incoming edge from , and so on: . There are only vertices, so this backward walk must repeat a vertex within steps. A repeated vertex on a directed walk means a directed cycle — contradicting "DAG." Hence some vertex has indegree 0. ✅ Induction: emit it and delete its out-edges; the remaining graph is still a DAG (removing edges can't create a cycle), so it also has an indegree-0 vertex. Repeating empties the graph — Kahn terminates and emits exactly vertices.

Exercise 5.3 (Reverse-graph trick)

Let be the running graph with every edge reversed. Claim: a valid topological order of is the reverse of a valid topological order of . Verify with the order from Exercise 2.1.

Recall Solution 5.3

If in , then in ; and if before in a -order, then after in its reverse — exactly what demands. So reversing a valid -order gives a valid -order. Reverse of is . Check against edges (): each edge points forward in . For instance : (pos 0) before (pos 1) ✅; : pos 1 before pos 2 ✅; : pos 3 before pos 4 ✅. All hold. Answer: is a valid topo order of . This trick underlies Kosaraju's algorithm for Strongly Connected Components.


Active Recall

Recall Rapid self-test (cover the answers)
  • Kahn on running graph, smallest-first order? :::
  • DFS-topo starting at 5 then 4, reversed order? :::
  • How many valid topo orders does the running graph have? ::: 13
  • Course-schedule graph : finishable? ::: No — form a cycle.
  • DAG shortest path from 4, unit weights: dist to 0 and 1? ::: both 1 (2,3,5 unreachable)
  • Reverse of as a order? :::

Connections

  • Parent: Topological Sort — the algorithms these exercises drill.
  • Depth-First Search (DFS) — used in Exercises 2.2, 5.1.
  • Breadth-First Search (BFS) — Kahn's engine in Exercises 2.1, 3.2, 4.1.
  • Directed Acyclic Graph (DAG) — the existence precondition (Ex 1.1, 5.2).
  • Cycle Detection in Directed Graphs — Exercise 4.1's core.
  • Course Schedule Problem — Exercise 4.1.
  • Shortest Path in DAG — Exercise 4.2.
  • Strongly Connected Components — Exercise 5.3's reverse-graph trick.