Worked Examples: Topological Sort & SCC

These examples are designed to step through the logical process of applying DAG and SCC concepts.

Example 1: Topological Sort (DFS)
❓ Problem: DAG: A→B, A→C, B→D, C→D. Give a valid topological order using DFS.
💡 Solution: DFS from A: Visit B→D (D finishes, B finishes), Visit C (C finishes), A finishes. Order by decreasing finish: A, C, B, D (or A, B, C, D also valid).
Example 2: Kahn's Algorithm
❓ Problem: Same DAG: A→B, A→C, B→D, C→D. Trace Kahn's algorithm.
💡 Solution: In-degrees: A:0, B:1, C:1, D:2. Queue=[A]. Dequeue A, decrement B,C. Queue=[B,C]. Dequeue B, decrement D. Queue=[C]. Dequeue C, decrement D. Queue=[D]. Result: A, B, C, D.
Example 3: Cycle Detection
❓ Problem: Graph: A→B, B→C, C→A, A→D. Is there a valid topological order?
💡 Solution: No! Cycle A→B→C→A exists. DFS would find a back edge. Kahn's would have output size < 4.
Example 4: SCC Identification
❓ Problem: Graph: 1→2, 2→3, 3→1, 3→4, 4→5, 5→4. How many SCCs?
💡 Solution: SCC 1: {1, 2, 3} (cycle 1→2→3→1). SCC 2: {4, 5} (cycle 4→5→4). Total: 2 SCCs.
Example 5: DAG Source Property
❓ Problem: Does every DAG have a source (in-degree 0)?
💡 Solution: Yes. If no source existed, following backward edges would eventually revisit a node, creating a cycle—contradicting the DAG property.
Example 6: Uniqueness of Topological Sort
❓ Problem: Is the topological sort of a DAG unique?
💡 Solution: No. If two nodes have no dependency between them, their order can be swapped. Example: nodes A, B with no edges—both A,B and B,A are valid.