Dependencies and topological order
After this: Put jobs in a valid order by counting what each one waits for, and spot a cycle.
On this page · 9 sections · 4 checks
So far, the edges in this tutorial have been roads, and their weights have been distances. This lesson uses the arrows of a directed graph for a different job: saying what must happen before what. The edges here have no weights.
Getting dressed
You have three jobs: put on socks, put on trousers, and put on shoes. The shoes must go on after the socks and after the trousers. An arrow from X to Y means "X must come before Y".
Which orders work?
- socks, trousers, shoes: this works.
- trousers, socks, shoes: this works too, because socks and trousers do not depend on each other.
- shoes, socks, trousers: this does not work, because the shoes go on first.
A rule like this is called a . The same shape turns up in course prerequisites, and in software, where one file must be built before another.
The name: topological order
A list of all the nodes in which every arrow points forward is called a .
An order can exist only if the arrows never lead you round in a loop. If X must come before Y and Y must come before X, you can never start. A loop like this is called a . A directed graph with no cycle is called a , short for directed acyclic graph. A DAG always has at least one topological order, and it often has several.
Three jobs, one row per step
To find an order, start with any job that is waiting for nothing. When it is done, cross out its arrows. Other jobs may now be waiting for nothing.
To do this, we count the arrows that point at each node. That number is the node's . A node with in-degree 0 is ready.
| Step | Take | Arrows removed | Still waiting | Ready list afterwards |
|---|---|---|---|---|
| Start | nothing | none | shoes 2 | socks, trousers |
| 1 | socks | socks→shoes | shoes 1 | trousers |
| 2 | trousers | trousers→shoes | shoes 0 | shoes |
| 3 | shoes | none | none | empty |
The order is socks, trousers, shoes. This method is called , after the person who published it. In general form:
- Count each node's in-degree. Every node at 0 goes on the ready list.
- Take a ready node and add it to the order.
- Remove its outgoing edges. Any neighbour that reaches 0 joins the ready list.
- Go back to step 2. Stop when nothing is ready.
The morning
Now we have five jobs. The arrows are wake→shower, wake→coffee, shower→dress, coffee→leave and dress→leave.
| Take | Edges removed | In-degrees after | Ready |
|---|---|---|---|
| start | wake 0, shower 1, coffee 1, dress 1, leave 2 | wake | |
| wake | wake→coffee, wake→shower | shower 0, coffee 0, dress 1, leave 2 | coffee, shower |
| coffee | coffee→leave | shower 0, dress 1, leave 1 | shower |
| shower | shower→dress | dress 0, leave 1 | dress |
| dress | dress→leave | leave 0 | leave |
| leave | empty |
The order is wake, coffee, shower, dress, leave.
After wake, coffee and shower were ready at the same time. We took coffee first, because the visualizer takes ready nodes in alphabetical order. The code below does the same here, because the graph lists each node's neighbours alphabetically. Taking shower first is also correct. An order is wrong only if an arrow points backwards, such as dress before shower.
The code
from collections import deque
def topological_order(graph): in_degree = {node: 0 for node in graph} for node in graph: for next_node in graph[node]: in_degree[next_node] += 1 # one more edge points at next_node ready = deque(node for node in graph if in_degree[node] == 0) order = [] while ready: node = ready.popleft() order.append(node) for next_node in graph[node]: in_degree[next_node] -= 1 # node is done: this edge no longer blocks next_node if in_degree[next_node] == 0: ready.append(next_node) if len(order) < len(graph): # some node never reached 0: a cycle return None return orderimport java.util.*;
public class TopologicalOrder { static List<String> of(Map<String, List<String>> graph) { Map<String, Integer> inDegree = new HashMap<>(); for (String node : graph.keySet()) inDegree.put(node, 0); for (List<String> targets : graph.values()) { for (String next : targets) inDegree.merge(next, 1, Integer::sum); // one more edge points at next } Deque<String> ready = new ArrayDeque<>(); for (String node : graph.keySet()) if (inDegree.get(node) == 0) ready.add(node); List<String> order = new ArrayList<>(); while (!ready.isEmpty()) { String node = ready.poll(); order.add(node); for (String next : graph.get(node)) { inDegree.merge(next, -1, Integer::sum); // node is done: this edge no longer blocks next if (inDegree.get(next) == 0) ready.add(next); } } if (order.size() < graph.size()) return null; // some node never reached 0: a cycle return order; }}Here is how to read it.
- This
graphhas no weights: each node maps to a list of the nodes that come after it. - The first loops count the in-degree of every node.
readystarts with every node at 0.- The
whileloop takes a ready node and adds it toorder. - The inner loop handles the outgoing edges. We do not really delete an edge. We lower the neighbour's count by one, which has the same effect.
- The last check compares the length of
orderwith the number of nodes. The next section explains why.
morning = { # neighbours listed alphabetically, as the visualizer does "wake": ["coffee", "shower"], "shower": ["dress"], "coffee": ["leave"], "dress": ["leave"], "leave": [],}print(" -> ".join(topological_order(morning)))wake -> coffee -> shower -> dress -> leave
Map<String, List<String>> morning = new LinkedHashMap<>(); // neighbours listed alphabetically, as the visualizer doesmorning.put("wake", List.of("coffee", "shower"));morning.put("shower", List.of("dress"));morning.put("coffee", List.of("leave"));morning.put("dress", List.of("leave"));morning.put("leave", List.of());System.out.println(String.join(" -> ", TopologicalOrder.of(morning)));wake -> coffee -> shower -> dress -> leave
Leftover nodes mean a cycle
What if the graph has a cycle? Take the edges A→B, B→C, C→B and C→D. B and C each wait for the other.
- The in-degrees are A 0, B 2, C 1 and D 1. Only A is ready.
- Take A. Removing A→B lowers B to 1.
- Nothing is ready now. B waits for C, C waits for B, and D waits for C.
The method stops with one node in the order and three left over. D is not on the cycle, but it is stuck behind it. This gives us a test: if the order is shorter than the graph, the graph has a cycle and no valid order exists. The code then returns Nonenull, so this program prints cycle.
cyclic = {"A": ["B"], "B": ["C"], "C": ["B", "D"], "D": []} # B -> C -> Border = topological_order(cyclic)print("cycle" if order is None else " -> ".join(order))cycle
Map<String, List<String>> cyclic = new LinkedHashMap<>(); // B -> C -> Bcyclic.put("A", List.of("B"));cyclic.put("B", List.of("C"));cyclic.put("C", List.of("B", "D"));cyclic.put("D", List.of());List<String> order = TopologicalOrder.of(cyclic);System.out.println(order == null ? "cycle" : String.join(" -> ", order));cycle
Watch it happen
The small number beside each node is its in-degree, and the ready list sits under the graph. Before the run, the task asks for a prediction: tap the node you think is taken first.
- Topological orderRun it. The small number at each node is its in-degree. The ready list holds the nodes at 0. Watch coffee and shower become ready together.
Run the topological order.
Now try a graph with a cycle.
- Topological orderRun it. A is taken, and then nothing is ready: B and C each wait for the other.
Run the topological order and watch it get stuck.
Check yourself
Which of these is a valid topological order of the morning graph? Every arrow must point forward in the order. More than one option is valid, so pick any one of them.
The edges are wake→shower, wake→coffee, shower→dress, coffee→leave and dress→leave. What are the in-degrees?
wake has now been taken. What is on the ready list, and which node is taken next if ready nodes are taken in alphabetical order?
Kahn's algorithm runs on a graph of five nodes and stops with only three in the order. What does that tell you?
Connect
- Say what a topological order is: a list of all the nodes in which every arrow points forward.
- Count in-degrees, take any node at 0, and remove its outgoing edges.
- Produce a valid order for the morning graph, and recognise the other valid orders.
- Say that leftover nodes mean a cycle, so no order exists.