getTopologicalSort
null if the graph is cyclic.
Complexity: O(V + E)
When to use:
- Build systems (compile dependencies in order)
- Task scheduling (prerequisite tasks)
- Package dependency resolution
- State machine ordering
- Course prerequisite planning
Example
Detecting cycles
Use Cases
Build system
Determine compilation order for source files with dependencies:Task scheduling
Schedule tasks respecting prerequisites:Course prerequisites
Determine valid course ordering:Package manager
Resolve installation order for package dependencies:Properties
Multiple valid orderings
A DAG can have multiple valid topological orderings:DAGs only
Topological sorting only works on directed acyclic graphs:Reverse postorder
Topological sort is equivalent to the reverse of DFS postorder on a DAG:Related Algorithms
isAcyclic()- Check if graph is a DAG before sortinggetPostorder()- DFS postorder (related to topological order)getCycles()- Find cycles that prevent topological sorting