DSA, Database System & Operating System — Sorting, Searching, and Graphs, NEC licence examination syllabus (Nepal Engineering Council).
Every build system, every task scheduler with dependencies, solves exactly this problem.
Topological sort only works on a DAG (Directed Acyclic Graph — no cycles) — it produces an ordering of vertices such that for every directed edge u→v, u appears BEFORE v in the ordering. Real example: "compile file B before file A" dependencies in a build system.
DFS-basedRun DFS, and add each vertex to the front of the result list the moment DFS finishes exploring all its descendants.
BFS-based (Kahn's algorithm)Repeatedly remove vertices that currently have zero incoming edges, adding them to the result, and reducing their neighbours' incoming-edge counts.
Take a dependency graph: A→C, B→C, C→D, C→E, D→F, E→F.
The algorithm does more than fail on a cyclic graph — it detects the cycle, which is often the actual point of running it.
All vertices outputThe graph is acyclic and the ordering is valid.
Queue empties earlyEvery remaining vertex still has an incoming edge, so they are waiting on each other — that is a cycle, and the remaining vertices are the ones involved in it.
In the trace above, A and B both start with in-degree zero, so B A C D E F is equally valid. Any vertex with no unmet dependencies may go next.
A topological sort is unique only when exactly one vertex has in-degree zero at every step — which means the graph is a single chain. Otherwise several orderings satisfy the constraints, and an exam question asking for "a" topological order will accept any of them.
Create a free account to tick topics off, take notes as you read, watch the video lessons and get a day-by-day study plan built around your exam date.
Loading…