La théorie des graphes, pas à pas

Cours gratuit
D'abord le quiz du chapitre 1

D'abord, vérifiez le chapitre 1

Faites le quiz du chapitre 1 : 10 questions, réussi avec 7 bonnes réponses. Vous pouvez le refaire autant de fois que vous voulez.

Order from Dependencies

Chapitre 2, leçon 3 sur 4

Topological sort: put tasks in an order where everything comes after what it depends on.

Narration en anglais. Activez les sous-titres anglais, arabes, allemands, espagnols ou français ci-dessus.

Leçon écrite

9 min de lectureRédigée en anglais.

Every morning you solve a graph problem. Socks before shoes. Trousers before shoes, and before the belt. The shirt before the belt and the tie, the tie and the belt before the jacket. The watch can go on whenever you like.

That is eight things to put on, and some must come before others. There are 40,320 ways to order eight things, but only 728 of them work. Finding one of them is called a topological sort, and it is how computers decide what to do first: which package to install, which file to compile, which cell of a spreadsheet to recalculate.

This lesson covers why such an order always exists when there are no cycles, two algorithms that find one and why they work, and how the same idea plans a whole building project.

Dependency graphs

Draw every item as a vertex, and draw an arrow from each item to the items that must come after it:

ItemMust come before
shirtbelt, tie
trousersbelt, shoes
socksshoes
tiejacket
beltjacket
shoes, jacket, watchnothing

The result is a directed graph with no cycles: a directed acyclic graph, or DAG for short. A topological order lines up all the vertices so that every arrow points forward.

A topological order: every arrow points forward.A topological order: every arrow points forward.

There is usually more than one. The watch depends on nothing and nothing depends on it, so it can go anywhere in the line.

Why an order always exists

Why must an order exist at all? Because every DAG has a vertex with no arrows coming in. Start anywhere, say at the jacket, and walk backwards along the arrows: to the belt, then to the trousers. Without a cycle you can never come back to a vertex you already passed, and there are only eight vertices, so the walk must stop. It can only stop at a vertex with nothing coming in.

Put that vertex first and remove it. What is left is still a DAG, so repeat. That builds a complete order, and it proves:

A directed graph has a topological order exactly when it has no cycle.

(The other direction is easy: around a cycle, some arrow would have to point backwards.)

Kahn's algorithm

The proof above is already an algorithm. For each vertex, count the arrows pointing into it: its in-degree. Anything with in-degree zero is ready to go.

  1. Put every ready item in a queue: shirt, socks, trousers, watch.
  2. Take the first one out, put it on, and remove its arrows, lowering the in-degree of each item it points to.
  3. Any item whose in-degree drops to zero joins the queue.
  4. Repeat until the queue is empty.

Taking the shirt drops the tie to zero, so the tie joins the queue. The trousers free the shoes and the belt, and the belt frees the jacket. The result is shirt, socks, trousers, watch, tie, shoes, belt, jacket, and every arrow points forward.

Kahn's algorithm: in-degrees, the queue of ready items, and the order so far.Kahn's algorithm: in-degrees, the queue of ready items, and the order so far.

Why it is always right. An item joins the queue only when its in-degree reaches zero, that is, when everything pointing to it has already been placed. So every arrow into an item comes from earlier in the line.

A few variations follow from the same idea:

  • The queue is not essential. Any ready item may go next, and each choice leads to a different valid order. If you always take the alphabetically first ready item, you get the alphabetically first of all 728 orders: shirt, socks, tie, trousers, belt, jacket, shoes, watch.
  • Rounds. You can also take every ready item at once. First the shirt, socks, trousers and watch; then the tie, shoes and belt; then the jacket. With enough helping hands that is three rounds, because the longest chain of arrows (for example shirt, tie, jacket) has three items.
  • Uniqueness. The order is unique exactly when the queue never holds two items at once. That happens only when every item in the line has an arrow to the very next one.

The DFS method

The second method uses depth-first search from the last lesson. When a vertex finishes, everything that must come after it has already finished. So write the vertices down in the order they finish, then reverse the list. That is a topological order too.

Taking the items in alphabetical order, the search finishes jacket, belt, tie, shirt, shoes, socks, trousers, watch. Reversed: watch, trousers, socks, shoes, shirt, tie, belt, jacket. A different order from Kahn's, and just as valid.

Why reversing works. Take any arrow from A to B. When the search looks along it, one of three things is true:

  1. B is new. It is explored from A, so it finishes before A.
  2. B has already finished. Then it finished before A too.
  3. B has started but not finished, so it is still on the current path. Then there is a path from B down to A, and the arrow from A back to B closes a cycle: a back edge, just like in the last lesson.

The three cases for an arrow from A to B during depth-first search.The three cases for an arrow from A to B during depth-first search.

In a DAG the third case cannot happen, so B always finishes first, and after reversing, A comes before B. That is why programs mark every vertex as new, in progress or finished: an arrow into a vertex that is in progress means there is a cycle, and no order exists.

When no order exists

Now suppose the jacket had to go on before the shirt. Shirt, tie, jacket and back to the shirt: that is a cycle. No order can work, because each of those three items would have to come before itself.

Kahn's algorithm notices on its own: the queue runs empty before everything is placed. Here it places socks, trousers, watch and shoes, and then nothing is ready. So the same algorithm doubles as a cycle detector: if the final order is shorter than the number of vertices, there was a cycle.

With the arrow from jacket to shirt, the queue empties with four items left: a cycle.With the arrow from jacket to shirt, the queue empties with four items left: a cycle.

It even shows where to look. Every item left over has an arrow coming in from another leftover item (otherwise its in-degree would have reached zero), so walking backwards among them must eventually loop. Here the leftovers are the belt, jacket, shirt and tie. Walk back from the jacket to the tie, then to the shirt, and you are back at the jacket.

The critical path

Builders face dependencies every day: the foundation before the walls, the walls before the roof. A topological order also answers a bigger question: how long will the whole project take? Give every task a duration, and let tasks run side by side whenever their prerequisites allow.

TaskDaysAfter
foundation4nothing
walls6foundation
plumbing3foundation
roof5walls
wiring2walls
plaster2plumbing, wiring
paint2roof, plaster

Go through the tasks in topological order. A task can start as soon as its slowest prerequisite is done, so its earliest start is the latest finish among the arrows coming in:

TaskEarliest startEarliest finish
foundation04
walls410
plumbing47
roof1015
wiring1012
plaster1214
paint1517

The house is finished after 17 days. The longest chain, foundation, walls, roof, paint (4 + 6 + 5 + 2), is the critical path: delay any task on it and the whole project slips. The plumbing, by contrast, could start as late as day 10 without delaying anything: it has 6 days to spare, its slack.

The critical path: foundation, walls, roof, paint.The critical path: foundation, walls, roof, paint.

It takes a single pass over a topological order, so it runs in linear time. Project managers call it the critical path method.

Software and Python

Software is full of dependency graphs. Package managers install libraries in dependency order, build tools compile files before the files that need them, and a spreadsheet recalculates a cell only after the cells it depends on (and reports an error when the formulas form a cycle).

In Python, Kahn's algorithm is short: count the in-degrees, put every ready vertex in a queue, and repeat. If the final order is shorter than the number of vertices, there was a cycle.

from collections import deque

def topo_sort(adj):
    indeg = {v: 0 for v in adj}
    for u in adj:
        for v in adj[u]:
            indeg[v] += 1
    queue = deque(v for v in adj if indeg[v] == 0)
    order = []
    while queue:
        u = queue.popleft()
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                queue.append(v)
    if len(order) < len(adj):
        raise ValueError("cycle")
    return order

dressing = {
    "belt": ["jacket"], "jacket": [], "shirt": ["belt", "tie"], "shoes": [],
    "socks": ["shoes"], "tie": ["jacket"], "trousers": ["shoes", "belt"], "watch": [],
}
topo_sort(dressing)
# ['shirt', 'socks', 'trousers', 'watch', 'tie', 'shoes', 'belt', 'jacket']

Kahn's algorithm in Python.Kahn's algorithm in Python.

Every vertex and every arrow is handled once, so it runs in linear time, O(n + m).

Key ideas

  • A dependency graph has an arrow from each task to the tasks that must wait for it. A topological sort lines the tasks up with every arrow pointing forward.
  • An order exists exactly when the graph has no cycle.
  • Kahn's algorithm takes ready tasks from a queue and doubles as a cycle detector. The DFS method reverses the finishing order.
  • With durations, one pass over a topological order finds the critical path of a whole project.

Check yourself

1. In the dressing graph, can the belt go on before the shirt?

2. In the house project, the wiring takes 2 days. How many days of slack does it have?

3. Kahn's algorithm returns 5 items for a graph with 7 vertices. What does that tell you?

Practice on the platform

The topological sort guide works through Kahn's algorithm step by step, and the project management guide goes further into the critical path. In the topological sort visualizer, import the dressing graph as a directed list and run it: shirt, socks, trousers, watch, tie, shoes, belt, jacket, the same order we found by hand. The critical path visualizer runs the building project.

À suivre

Contenu du cours

0 sur 20 vues

Chapitre 1Graph Theory Foundations

Chapitre 2Exploring a GraphD'abord le quiz du chapitre 1

Chapitre 3Shortest PathsD'abord le quiz du chapitre 2

Chapitre 4Connecting CheaplyD'abord le quiz du chapitre 3

Chapitre 5Hard ProblemsD'abord le quiz du chapitre 4

Chapitre 6Network FlowsD'abord le quiz du chapitre 5