Data Structures and Algorithms • C# examples
Topological Sorting and Dependency Ordering
Order directed acyclic graph tasks so every prerequisite appears before its dependent.
Concept
A topological order exists only for a directed acyclic graph (DAG). Kahn’s algorithm repeatedly removes zero-indegree vertices; a DFS finishing order provides another approach. If fewer than V vertices are emitted, the graph contains a directed cycle.
How to approach it
Track indegrees and enqueue every currently available vertex; decrement neighbors as prerequisites are removed.
Complexity
O(V + E) time and O(V) additional space.
C# example
var ready = new Queue<int>(Enumerable.Range(0, n).Where(v => indegree[v] == 0));
var order = new List<int>();
while (ready.TryDequeue(out int v))
{
order.Add(v);
foreach (int next in graph[v])
if (--indegree[next] == 0) ready.Enqueue(next);
}
bool isDag = order.Count == n;
Expected result or behavior
A full order is returned only when every vertex can be removed.
Practice exercise
Use course prerequisites as a graph and identify what a leftover vertex implies.
Key takeaway: Topological order exists precisely when the directed dependency graph is acyclic.