Topological sort of a directed graph
Problem Given a directed acyclic graph (DAG) with V vertices and E edges, return a valid topological ordering of its vertices — an ordering in which, for every directed edge u -> v, u appears before v. If the graph contains a cycle, report that no valid ordering exists.
Input / Output
- Input: number of vertices and a list of directed edges (adjacency list).
- Output: a list of vertices in a valid topological order (any valid order is accepted), or an indication that none exists.
Constraints
- 1 <= V <= 10^5, 0 <= E <= 2*10^5. Multiple valid orderings may exist.
Example
- Edges 5->2, 5->0, 4->0, 4->1, 2->3, 3->1 -> a valid order is [4, 5, 2, 3, 1, 0].
asked …