A topological order lists the vertices of a directed acyclic graph so every edge u -> v has u before v. Kahn's algorithm: compute each vertex's in-degree, queue the vertices with in-degree 0, and repeatedly remove one, decrementing the in-degree of its neighbors and queueing any that reach 0. If fewer than V vertices are output, the graph has a cycle.
Remember
queue all vertices with indegree 0
while queue not empty:
u = dequeue(); output u
for each edge u -> v: if --indegree[v] == 0: enqueue(v)
if output count < V: cycle
Reference
Cheat Sheet
Keep these facts handy while you work with Topological Sorting in C in C.
#include <stdio.h>
#define V 6
static int topo(int adj[V][V], int out[V]) {
int indeg[V] = {0}, q[V], head = 0, tail = 0, n = 0;
for (int u = 0; u < V; u++)
for (int v = 0; v < V; v++) indeg[v] += adj[u][v];
for (int v = 0; v < V; v++) if (indeg[v] == 0) q[tail++] = v;
while (head < tail) {
int u = q[head++];
out[n++] = u;
for (int v = 0; v < V; v++)
if (adj[u][v] && --indeg[v] == 0) q[tail++] = v;
}
return n;
}
int main(void) {
int adj[V][V] = {{0}}, out[V];
int edges[][2] = {{5, 2}, {5, 0}, {4, 0}, {4, 1}, {2, 3}, {3, 1}};
for (int i = 0; i < 6; i++) adj[edges[i][0]][edges[i][1]] = 1;
int n = topo(adj, out);
printf("topological order:");
for (int i = 0; i < n; i++) printf(" %d", out[i]);
printf("\n");
int cyc[V][V] = {{0}};
cyc[0][1] = cyc[1][2] = cyc[2][1] = 1;
n = topo(cyc, out);
printf("cyclic graph: %d of %d vertices ordered -> %s\n", n, V, n < V ? "cycle detected" : "ok");
return 0;
}
In the cyclic graph, edges 1->2 and 2->1 keep vertices 1 and 2 above in-degree 0 forever, so only the other four vertices are ordered (4 of 6) and the shortfall reveals the cycle.
Edge Cases & Pitfalls
Check these before relying on Topological Sorting in C in real programs.
ties
Many valid orders
A DAG usually has several topological orders; yours depends on tie-breaking.
cyc
Ignoring cycle detection
Always compare the output count with the vertex count.
Remember
Key Takeaways
Queue the in-degree 0 vertices.
Decrement neighbors.
Count to detect cycles.
One line: A topological order lists the vertices of a directed acyclic graph so every edge u -> v has u before v.
Frequently Asked Questions
Scheduling tasks with dependencies, build systems, course prerequisites, and resolving dependency order.
No. A valid topological order exists only for directed acyclic graphs.
Continue with "Shortest Path Basics in C" next. Find shortest hop paths with BFS and learn edge relaxation. The C Graph Algorithms hub lists every topic in order.