8.3Graph Applications
Topological sort
Courses in a department have prerequisites: you cannot take Algorithms before Data Structures. When software is built, every module must be compiled after the modules it uses. Dependencies like these form a directed graph; the edge u→v means "u before v". A topological sort lists all the tasks in an order that keeps these rules. In this lesson you write Kahn's algorithm, which does it with a queue.
- What a topological order is and why it exists only in a DAG
- Kahn's algorithm, which builds the order with in-degrees and a queue
- How the same function notices that the graph has a cycle
1Idea
A task with no prerequisites, that is with no incoming edges, can be done right away. The number of edges coming into a vertex is called its in-degree. Kahn's algorithm first counts the in-degree of every vertex and puts the ones with in-degree 0 into a queue.
The vertex taken out of the queue is written into the order. Since it is done now, its outgoing edges count as removed: the in-degree of each neighbour drops by one. A neighbour whose in-degree falls to 0 has had its last prerequisite done; it joins the queue too. When the queue is empty, the work is over.
If the graph has a cycle, each vertex on the cycle waits for the one before it, and none of their in-degrees ever reaches 0. These vertices never get into the order. That is why the function compares the number of vertices written with n at the end: if some are missing, the graph is not a DAG and has no topological order. So Kahn's algorithm is a second way of finding a cycle.
Topological order with DFS
The second way is DFS. The call of a vertex finishes after every vertex reachable from it has finished. If you push vertices onto a stack as they finish and then empty the stack, that is if you take the reverse of the finishing order, u comes before v for every edge u→v. Both methods take O(V + E) time; they often give different orders, and both are correct.
A DAG usually has more than one topological order. In the example the order is still right if 4 and 5 swap places. When an exam asks for an order, putting tied vertices into the queue from the smallest number to the largest gives one answer that can be checked.
2Step by step
The drawing shows a DAG with 6 vertices. The in value under a vertex is its in-degree. The orange vertex has just left the queue and the orange arrows are its removed edges; the green ones are already in the order. The queue is shown under the drawing.
- The in-degrees are counted: two edges come into 0 and into 1, one into 2 and into 3; none into 4 and 5.
- 4 and 5, with in-degree 0, join the queue. These are the tasks with no prerequisites.
- 4 leaves and is written into the order. Its edges are removed: the in-degree of 0 drops to 1 and that of 1 to 1. Order: 4.
- 5 leaves and is written. Its neighbours are read from small to large: first the in-degree of 0 becomes 0, then that of 2; both join the queue in that order. Order: 4 5.
- 0 leaves and is written. 0 has no outgoing edges. Order: 4 5 0.
- 2 leaves and is written. The in-degree of 3 becomes 0 and it joins the queue. Order: 4 5 0 2.
- 3 leaves and is written. The in-degree of 1 becomes 0 and it joins the queue. Order: 4 5 0 2 3.
- 1 leaves and is written. The queue is empty. Order: 4 5 0 2 3 1.
- All 6 of the 6 vertices made it into the order: the graph has no cycle and the function returns true.
#define MAX 8 struct Node { int data; struct Node* next;}; struct Graph { int n; bool directed; struct Node* adj[MAX];}; bool topologicalSort(struct Graph* g, int order[]) { int indeg[MAX] = {0}; for (int u = 0; u < g->n; u++) // count the in-degrees for (struct Node* p = g->adj[u]; p != NULL; p = p->next) indeg[p->data]++; int queue[MAX], front = 0, rear = 0; for (int u = 0; u < g->n; u++) if (indeg[u] == 0) queue[rear++] = u; // no prerequisites int k = 0; while (front < rear) { int u = queue[front++]; order[k++] = u; // u can be done now for (struct Node* p = g->adj[u]; p != NULL; p = p->next) if (--indeg[p->data] == 0) // its last prerequisite is done queue[rear++] = p->data; } return k == g->n; // missing ones: a cycle}class Node { int data; Node next; Node(int data) { this.data = data; }} class ListGraph { int n; boolean directed; Node[] adj; ListGraph(int n, boolean directed) { this.n = n; this.directed = directed; adj = new Node[n]; }} boolean topologicalSort(ListGraph g, int[] order) { int[] indeg = new int[g.n]; for (int u = 0; u < g.n; u++) // count the in-degrees for (Node p = g.adj[u]; p != null; p = p.next) indeg[p.data]++; java.util.ArrayDeque<Integer> queue = new java.util.ArrayDeque<>(); for (int u = 0; u < g.n; u++) if (indeg[u] == 0) queue.add(u); // no prerequisites int k = 0; while (!queue.isEmpty()) { int u = queue.poll(); order[k++] = u; // u can be done now for (Node p = g.adj[u]; p != null; p = p.next) if (--indeg[p.data] == 0) // its last prerequisite is done queue.add(p.data); } return k == g.n; // missing ones: a cycle}from collections import deque class Node: def __init__(self, data): self.data = data self.next = None class ListGraph: def __init__(self, n, directed=False): self.n = n self.directed = directed self.adj = [None] * n def topological_sort(g, order): indeg = [0] * g.n for u in range(g.n): # count the in-degrees p = g.adj[u] while p is not None: indeg[p.data] += 1 p = p.next queue = deque(u for u in range(g.n) if indeg[u] == 0) # no prerequisites k = 0 while queue: u = queue.popleft() order[k] = u # u can be done now k += 1 p = g.adj[u] while p is not None: indeg[p.data] -= 1 if indeg[p.data] == 0: # its last prerequisite is done queue.append(p.data) p = p.next return k == g.n # missing ones: a cycleThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Counting the in-degrees reads every list once; after that every vertex enters the queue once and every edge is removed once: O(V + E).
The in-degrees and the queue hold V elements.
With an adjacency matrix the same method takes O(V²) time: finding the neighbours of a vertex means reading its whole row.
4Common mistake
A common mistake is putting a vertex into the queue as soon as its in-degree drops:
indeg[p->data]--;queue[rear++] = p->data; // it may still have prerequisitesIn the example, when 4 leaves, the in-degree of 0 drops to 1, but 0 is still waiting for 5. With this code 0 can be written before 5, which breaks the rule 5→0; the same vertex also enters the queue more than once. A vertex goes into the queue only when its in-degree reaches 0. The second mistake is not checking the count at the end: on a graph with a cycle the function hands back an incomplete order as if it were right.
5Try it
For the graph with edges 0→1, 0→2, 1→3, 2→3, which one is not a topological order?
The answer is C. The edge 2→3 needs 2 before 3. In 0 1 3 2, 3 is written before 2.
Show the answer
The answer is C. The edge 2→3 needs 2 before 3. In 0 1 3 2, 3 is written before 2.
When Kahn's algorithm ends, only 4 of the 7 vertices of a graph are in the order. What does that tell you?
The answer is B. The in-degree of a vertex on a cycle never reaches 0, so it never gets into the order. All the vertices of a DAG that is not connected still get in.
Show the answer
The answer is B. The in-degree of a vertex on a cycle never reaches 0, so it never gets into the order. All the vertices of a DAG that is not connected still get in.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.