A detailed walkthrough of topological sort using a humorous Martian Stew recipe as a dependency graph example. Covers the problem of ordering tasks with dependencies, introduces directed acyclic graphs (DAGs) and cycle detection, then explains and compares two canonical algorithms: Kahn's algorithm (using dependency counts and a pending set) and the depth-first search variant. Also discusses adjacency list vs. adjacency matrix graph representations and their trade-offs. Complete Python implementations are provided for both algorithms, including cycle detection.
Table of contents
Martian Stew: Rattle your DAGsAlgorithm 1: Kahn’s AlgorithmAlgorithm 2: Depth-first SearchWhich is better?Representing graphsPython code for topological sortWrapup4 Impressions