Kodewick
Start learning →
Topological sort31 / 50

Topological sort

Lesson 31 of 50 · Part 6 · Graphs · about 15 minutes

A topological sort orders the vertices of a directed graph so that every edge points forward, by repeatedly taking out a vertex with in-degree 0; if vertices are left that can't be taken out, the graph has a cycle and no such order exists.

Computer science courses have prerequisites: data structures needs programming and discrete maths first, operating systems needs data structures and computer organization… With six courses, you want an order to take them in, each one after all its prerequisites. A compiler deciding which file to build first, make deciding which target to make first, a spreadsheet deciding which cell to work out first: it's all one problem, topological sort.

Prerequisites are a directed graph

One vertex per course, and an edge A → B for "A is a prerequisite of B". The order wanted is one where every edge's start comes before its end.

Such an order exists if and only if the graph has no cycle: if A must come before B, B before C, and C before A, none of them can go first. A directed graph with no cycle is a directed acyclic graph (DAG).

Which course can come first? One with no prerequisites, that is, with in-degree 0. Once it's done, the edges out of it don't matter any more, so delete them; then some other courses' in-degree drops to 0… That's Kahn's algorithm:

  1. Work out every vertex's in-degree, and queue those with in-degree 0.
  2. While the queue isn't empty: take out u and output it; for each v that u points to, subtract 1 from v's in-degree, and queue v when it reaches 0.

queue

Six courses and their prerequisites. The number on a vertex is its in-degree now; when a course is output, the edges out of it are deleted (faded)
Choose one

Which set of prerequisites can't be put in any order?

Choose one

Directed edges B → A, B → D, C → A, A → E, D → E. Run Kahn's algorithm, queueing vertices in alphabetical order when several reach in-degree 0 together. What order comes out?

In C: an in-degree table and a queue

This level writes Kahn's algorithm in C. The graph is stored as an adjacency matrix: a[u][v] = 1 means there's an edge u → v, so the number of 1s in column v is v's in-degree. The queue is just an array q with two indexes: q[rear++] = v puts v in, q[front++] takes one out, and front < rear means something is still waiting. It's the six-course example again, numbered 0 to 5: C, DM, DS, CO, Alg, OS.

Each vertex goes in and out of the queue once, and each edge lowers an in-degree once: O(n + e) with an adjacency list, O(n²) with an adjacency matrix.

main.c
1#include <stdio.h>2 3#define N 64 5const char *name[N] = {"Programming in C", "Discrete maths", "Data structures", "Computer organization", "Algorithms", "Operating systems"};6int a[N][N];                 // a[u][v] = 1: u is a prerequisite of v7 8int topo(int order[]) {      // returns how many it got out9    int indeg[N] = {0}, q[N], front = 0, rear = 0, k = 0;10    for (int u = 0; u < N; u++)11        for (int v = 0; v < N; v++)12            indeg[v] += a[u][v];13    for (int v = 0; v < N; v++)14        if (indeg[v] == 0) q[rear++] = v;15    while (front < rear) {16        int u = q[front++];17        order[k++] = u;18        for (int v = 0; v < N; v++)19            if (a[u][v] && --indeg[v] == 0)   // delete u → v; queue v when it reaches 020                q[rear++] = v;21    }22    return k;23}24 25int main(void) {26    a[0][2] = a[1][2] = a[0][3] = 1;27    a[2][4] = a[1][4] = a[2][5] = a[3][5] = 1;28    int order[N];29    int k = topo(order);30    for (int i = 0; i < k; i++)31        printf("%d. %s\n", i + 1, name[order[i]]);32    printf(k == N ? "all sorted\n" : "a cycle: can't sort them all\n");33    return 0;34}
Output
1. Programming in C
2. Discrete maths
3. Computer organization
4. Data structures
5. Algorithms
6. Operating systems
all sorted
Fill inTap one to fill a blank; tap a blank to take it back

Which condition makes the while loop handle every vertex in the queue? The program should print 0 1 3 2 4 5.

1#include <stdio.h>2 3#define N 64 5int a[N][N];6 7int main(void) {8    a[0][2] = a[1][2] = a[0][3] = 1;9    a[2][4] = a[1][4] = a[2][5] = a[3][5] = 1;10    int indeg[N] = {0}, q[N], front = 0, rear = 0;11    for (int u = 0; u < N; u++)12        for (int v = 0; v < N; v++)13            indeg[v] += a[u][v];14    for (int v = 0; v < N; v++)15        if (indeg[v] == 0) q[rear++] = v;16    while () {17        int u = q[front++];18        printf("%d ", u);19        for (int v = 0; v < N; v++)20            if (a[u][v] && --indeg[v] == 0)21                q[rear++] = v;22    }23    printf("\n");24    return 0;25}
Choose one

A graph with n vertices and e edges is stored as an adjacency matrix, as in this level's program. How long does Kahn's algorithm take?

Exercise 1

Write Kahn's algorithm

Fill in two places: first work out each vertex's in-degree from the adjacency matrix; then, in the while loop, print what comes out, subtract 1 from the in-degree of each vertex it points to, and queue any that reach 0.

It should print
0 5 1 2 6 3 4
exercise1.c
1#include <stdio.h>2 3#define N 74 5int a[N][N];6 7int main(void) {8    a[0][1] = a[0][2] = a[1][3] = a[2][3] = 1;9    a[3][4] = a[5][2] = a[5][6] = a[6][4] = 1;10    int indeg[N] = {0}, q[N], front = 0, rear = 0;11    // 1. indeg[v] = how many 1s in column v12    for (int v = 0; v < N; v++)13        if (indeg[v] == 0) q[rear++] = v;14    while (front < rear) {15        int u = q[front++];16        // 2. print u; for each v: if a[u][v] is 1, indeg[v]--, and queue v when it reaches 017    }18    printf("\n");19    return 0;20}
Output
Press Run or Ctrl+Enter
Exercise 2

The earliest term for each course

You can take any number of courses in a term, but a course can only be taken the term after all its prerequisites are done. Courses with no prerequisites are in term 1. Go in topological order: when deleting the edge u → v, sem[v] is at least sem[u] + 1. Fill in that line, and print each course's earliest term.

It should print
1 1 2 2 3 3
exercise2.c
1#include <stdio.h>2 3#define N 64 5int a[N][N];6 7int main(void) {8    a[0][2] = a[1][2] = a[0][3] = 1;9    a[2][4] = a[1][4] = a[2][5] = a[3][5] = 1;10    int indeg[N] = {0}, sem[N], q[N], front = 0, rear = 0;11    for (int u = 0; u < N; u++)12        for (int v = 0; v < N; v++)13            indeg[v] += a[u][v];14    for (int v = 0; v < N; v++) {15        sem[v] = 1;16        if (indeg[v] == 0) q[rear++] = v;17    }18    while (front < rear) {19        int u = q[front++];20        for (int v = 0; v < N; v++)21            if (a[u][v]) {22                // sem[v] becomes the bigger of sem[v] and sem[u] + 123                if (--indeg[v] == 0) q[rear++] = v;24            }25    }26    for (int v = 0; v < N; v++)27        printf("%d ", sem[v]);28    printf("\n");29    return 0;30}
Output
Press Run or Ctrl+Enter

Topological orders aren't unique

At the start, C and discrete maths both have in-degree 0, and either can go first; later, so can algorithms and OS. So there's usually more than one topological order: C DM DS CO OS Alg is right too, and so is DM C CO DS Alg OS. All that matters is that every edge points forward. Swap the queue for a stack and it's still a correct topological sort, just giving another order:

Guess the outputA wrong guess is fine

The same graph with the queue swapped for a stack. What does it print?

1#include <stdio.h>2 3#define N 64 5int a[N][N];6 7int main(void) {8    a[0][2] = a[1][2] = a[0][3] = 1;9    a[2][4] = a[1][4] = a[2][5] = a[3][5] = 1;10    int indeg[N] = {0}, st[N], top = 0;11    for (int u = 0; u < N; u++)12        for (int v = 0; v < N; v++)13            indeg[v] += a[u][v];14    for (int v = 0; v < N; v++)15        if (indeg[v] == 0) st[top++] = v;16    while (top > 0) {17        int u = st[--top];18        printf("%d ", u);19        for (int v = 0; v < N; v++)20            if (a[u][v] && --indeg[v] == 0)21                st[top++] = v;22    }23    printf("\n");24    return 0;25}

There's also a way with DFS: run DFS from every vertex, note each vertex as it returns, once everything after it is finished, and reverse the noted order to get a topological order: the first to finish is the course with nothing after it, which belongs last anyway. Exams and interviews use Kahn more, because it checks for cycles along the way.

Choose one

The six-course graph: edges 0 → 2, 1 → 2, 0 → 3, 2 → 4, 1 → 4, 2 → 5, 3 → 5. Which one is not a topological order?

Choose one

The same graph done with DFS: starting at 0, neighbours smallest first, the vertices finish (return) in the order 4 5 2 3 0 1. What topological order does that give?

Not all out means a cycle

Kahn's algorithm checks for cycles by itself: with a cycle, the vertices on it wait for each other, their in-degrees never reach 0, and none of them ever gets into the queue. So the loop ends early, with fewer than n output.

Fill in one prerequisite wrongly: "algorithms is also a prerequisite of data structures". DS → Alg and Alg → DS: the two courses wait for each other, a cycle.

queue

One edge too many, Alg → DS: DS and Alg are each other's prerequisite, and the two opposite edges are drawn as two arcs

Put the extra edge 4 → 2 into Kahn's program and run it:

main.c
1#include <stdio.h>2 3#define N 64 5int a[N][N];6 7int topo(int order[]) {8    int indeg[N] = {0}, q[N], front = 0, rear = 0, k = 0;9    for (int u = 0; u < N; u++)10        for (int v = 0; v < N; v++)11            indeg[v] += a[u][v];12    for (int v = 0; v < N; v++)13        if (indeg[v] == 0) q[rear++] = v;14    while (front < rear) {15        int u = q[front++];16        order[k++] = u;17        for (int v = 0; v < N; v++)18            if (a[u][v] && --indeg[v] == 0)19                q[rear++] = v;20    }21    return k;22}23 24int main(void) {25    a[0][2] = a[1][2] = a[0][3] = 1;26    a[2][4] = a[1][4] = a[2][5] = a[3][5] = 1;27    a[4][2] = 1;                                  // an extra 4 → 2: each is the other's prerequisite28    int order[N];29    int k = topo(order);30    printf("got %d out: ", k);31    for (int i = 0; i < k; i++)32        printf("%d ", order[i]);33    printf("\n%s\n", k == N ? "all sorted" : "a cycle: can't sort them all");34    return 0;35}
Output
got 3 out: 0 1 3 
a cycle: can't sort them all

Forget to check k == N and the program happily prints three courses, 0 1 3, looking for all the world like a finished order. Topological sort code must always compare the count at the end.

Kahn (in-degree + queue)DFS
Orderin-degree 0 goes firstfinishing order, reversed
Cycle checkfewer than n outputreaching a vertex "still in the recursion"
TimeO(n + e)O(n + e)

In exams: "write all the topological orders of this graph": at each step try every vertex whose in-degree is 0 now, and count them as a tree. "If a directed graph's adjacency matrix is upper triangular (all 0 below the diagonal), it has a topological order": every edge goes from a smaller number to a bigger one, so 0 1 2 … n − 1 is one. There's also the AOE network and its critical path: in topological order work out each event's earliest time (taking the maximum), then work backwards for the latest times; the activities where the two match are on the critical path.

Guess the outputA wrong guess is fine

Directed edges 0 → 1, 1 → 2, 2 → 3, 3 → 1, 0 → 4. How many vertices does Kahn's algorithm get out?

1#include <stdio.h>2 3#define N 54 5int a[N][N];6 7int main(void) {8    a[0][1] = a[1][2] = a[2][3] = a[3][1] = a[0][4] = 1;9    int indeg[N] = {0}, q[N], front = 0, rear = 0, k = 0;10    for (int u = 0; u < N; u++)11        for (int v = 0; v < N; v++)12            indeg[v] += a[u][v];13    for (int v = 0; v < N; v++)14        if (indeg[v] == 0) q[rear++] = v;15    while (front < rear) {16        int u = q[front++];17        k++;18        for (int v = 0; v < N; v++)19            if (a[u][v] && --indeg[v] == 0)20                q[rear++] = v;21    }22    printf("%d\n", k);23    return 0;24}
Choose one

A directed graph's adjacency matrix is upper triangular (the diagonal and everything below it are 0). What can you say about its topological orders?

Summary

Take-away

Topological sort: keep taking out in-degree 0

  • Only a DAG has a topological order, and usually more than one
  • Kahn: queue in-degree 0; take one out, lower its targets' in-degrees, queue any at 0
  • Fewer than n out means a cycle: always compare the count at the end
  • O(n + e); the DFS way reverses the finishing order
1while (front < rear) {2    int u = q[front++];3    order[k++] = u;4    for (int v = 0; v < N; v++)5        if (a[u][v] && --indeg[v] == 0) q[rear++] = v;6}