Some tasks must happen before others: you take Programming in C before Data Structures, and you compile a library before the program that uses it. If these “must come before” rules are drawn as arrows, a topological sort lists every task in an order that respects all the arrows. It only exists when there are no circular requirements, so the same algorithms also tell you whether a set of dependencies contains a cycle.
In this lesson you will learn
- Directed acyclic graphs (DAGs) and in-degree
- Kahn’s algorithm using a queue
- The DFS-based topological sort
- Detecting cycles in directed graphs
- Real uses: build systems, course planning, spreadsheets
This lesson builds on Graphs, BFS and DFS.
Kahn’s Algorithm
#include <stdio.h>
/* Kahn's algorithm: repeatedly take a vertex with no remaining prerequisites */
#define V 6
const char *course[V] = {"Intro", "C", "DSA", "Databases", "Web", "Project"};
int adj[V][V]; /* adj[u][v] = 1 means u must come before v */
int main(void) {
int edges[][2] = {{0, 1}, {1, 2}, {0, 3}, {3, 4}, {2, 5}, {4, 5}};
int indegree[V] = {0};
for (int i = 0; i < 6; i++) {
adj[edges[i][0]][edges[i][1]] = 1;
indegree[edges[i][1]]++;
}
int queue[V], head = 0, tail = 0;
for (int v = 0; v < V; v++) if (indegree[v] == 0) queue[tail++] = v;
int done = 0;
printf("Study order: ");
while (head < tail) {
int u = queue[head++];
printf("%s ", course[u]);
done++;
for (int v = 0; v < V; v++) {
if (adj[u][v] && --indegree[v] == 0) queue[tail++] = v;
}
}
printf("\n");
if (done < V) printf("Cycle detected: no valid order exists\n");
return 0;
}
Output
Study order: Intro C Databases DSA Web Project
- An edge
u → vmeans “u before v”. The in-degree of a vertex is the number of arrows pointing into it, that is, its unmet prerequisites. - Courses with in-degree 0 can be taken immediately, so they start in the queue. Here that is only Intro.
- Each time a course is taken, every course that depended on it loses one prerequisite. When a count reaches 0, that course joins the queue.
- Project appears last because it needs both DSA and Web.
- If the loop ends before every vertex was output, the leftover vertices are stuck waiting on each other: a cycle.
DFS-Based Topological Sort
#include <stdio.h>
/* DFS-based topological sort with cycle detection (0 = unvisited, 1 = on path, 2 = done) */
#define V 5
int adj[V][V], state[V], order[V], pos;
int has_cycle = 0;
void dfs(int u) {
state[u] = 1;
for (int v = 0; v < V; v++) {
if (!adj[u][v]) continue;
if (state[v] == 1) has_cycle = 1; /* back edge */
else if (state[v] == 0) dfs(v);
}
state[u] = 2;
order[--pos] = u; /* add to the FRONT when finished */
}
void run(const char *title, int edges[][2], int e) {
for (int i = 0; i < V; i++) { state[i] = 0; for (int j = 0; j < V; j++) adj[i][j] = 0; }
for (int i = 0; i < e; i++) adj[edges[i][0]][edges[i][1]] = 1;
pos = V; has_cycle = 0;
for (int u = 0; u < V; u++) if (state[u] == 0) dfs(u);
printf("%s: ", title);
if (has_cycle) { printf("cycle, no ordering\n"); return; }
for (int i = 0; i < V; i++) printf("%d ", order[i]);
printf("\n");
}
int main(void) {
int dag[][2] = {{0, 2}, {1, 2}, {2, 3}, {3, 4}, {1, 4}};
int cyc[][2] = {{0, 1}, {1, 2}, {2, 0}, {3, 4}};
run("DAG", dag, 5);
run("With cycle", cyc, 4);
return 0;
}
Output
DAG: 1 0 2 3 4
With cycle: cycle, no ordering
- A vertex is placed in the answer only after all vertices reachable from it are finished, and it is written to the front of the array (
order[--pos]). Reading the array from the start gives a valid order. - Three colours track progress: 0 unvisited, 1 on the current DFS path, 2 finished.
- Meeting a vertex that is still in state 1 means the path has looped back on itself, a back edge, so the graph has a cycle and no ordering exists.
- Both algorithms run in O(V + E) with adjacency lists. The examples use a matrix for simplicity, which is O(V2).
Kahn vs DFS
| Kahn (BFS) | DFS | |
|---|---|---|
| Main tool | Queue and in-degree counts | Recursion and finish order |
| Cycle detection | Fewer than V vertices output | A back edge to a vertex on the current path |
| Easy to adapt | Smallest-first order with a priority queue; parallel “levels” | Already doing DFS for other reasons |
| Time | O(V + E) | O(V + E) |
A DAG usually has many valid orders. Intro, Databases, C, Web, DSA, Project would also be correct for the course example.
Common Mistakes
- Getting the edge direction backwards, which produces the reverse order.
- Forgetting the cycle check and printing a partial order as if it were complete.
- Using a simple visited flag in DFS; you need to know whether a vertex is still on the current path to detect cycles.
- Applying topological sort to undirected graphs, where it is not defined.
Practice Exercises
Exercise 1. Give a valid order for tasks A→B, A→C, B→D, C→D.
Show answer
A, B, C, D (or A, C, B, D). A has no prerequisites, and D must wait for both B and C.
Exercise 2. Modify Kahn’s algorithm to print the minimum number of semesters needed, taking any number of available courses per semester.
Show answer
int semesters = 0;
while (head < tail) {
int level_end = tail; /* everything currently available */
semesters++;
while (head < level_end) {
int u = queue[head++];
for (int v = 0; v < V; v++)
if (adj[u][v] && --indegree[v] == 0) queue[tail++] = v;
}
}
printf("Semesters: %d\n", semesters); /* 4 for the course example */
Frequently Asked Questions
Where is topological sorting used?
Build tools such as make order compilation steps with it, package managers install dependencies in a valid order, spreadsheets recalculate cells after the cells they depend on, and university systems check course prerequisites.
Is the topological order unique?
Only when the order is forced at every step, which happens exactly when the DAG has a path through all its vertices. Otherwise several orders are valid.
Summary
- A topological order respects every “before” arrow in a DAG.
- Kahn’s algorithm repeatedly removes vertices with in-degree 0.
- The DFS method outputs vertices in reverse finishing order.
- Both run in O(V + E) and detect cycles.
