Python 3D Academyবাংলা

Directed acyclic graphs: things that must come first

🌍 In real life. Getting dressed: socks before shoes, underwear before trousers, trousers before shoes, shirt before jacket. Some things must come before others, many pairs don't care (socks and shirt can go in either order), and nothing can come before itself. A university's courses are the same: you can take Algorithms only after Programming and Maths.

This is a directed graph: each arrow says "this before that". When the arrows never lead round in a circle, it is a directed acyclic graph (DAG), and its jobs can always be put in a line that respects every arrow, called a topological order. This chapter finds such orders, and spots the cycles that make them impossible.

The idea in one sentence: a DAG is a directed graph with no cycle, and a topological order lists its vertices so that every arrow a → b has a before b; every DAG has at least one, and a graph with a cycle has none.

Its words:

  • directed edge (arrow) a → b: a must come before b
  • in-degree: how many arrows point into a vertex (how many things must come before it)
  • out-degree: how many arrows leave it
  • source: a vertex with in-degree 0; nothing has to come before it, so it can go first
  • DAG: a directed graph where following arrows never leads back to where you started
  • topological order: a line of all the vertices that every arrow points forward along

How to check an order, step by step:

  1. note each vertex's position in the order
  2. for every arrow a → b, check that a's position is before b's
  3. the order is valid only if every arrow passes

Watch one valid order come together for getting dressed (A underwear, B trousers, C socks, D shoes, E shirt, F jacket). The "in" label under each item is its in-degree, the number of arrows still coming in:

Why a DAG always has an order, and a cycle never does. In a DAG there is always a source. Start anywhere and walk backwards along arrows: with no cycle you can never revisit a vertex, so the walk must stop, at a vertex nothing points to. Put that source first, remove it, and what is left is still a DAG, so it has a source too; repeating this lists every vertex with all arrows pointing forward. With a cycle, say a → b → c → a, each vertex on it would have to come before the next, so a would have to come before itself, which is impossible. Many DAGs have several valid orders: socks and shirt can swap places.

What it costs, by counting. Checking an order is one pass over the vertices to note positions and one over the arrows: O(V + E). Working out every in-degree is the same: each arrow adds one to its target. For the six items and four arrows, that is 6 + 4 small steps.

def in_degrees(graph):
    indeg = {v: 0 for v in graph}        # every vertex, even one nothing points to
    for v in graph:
        for w in graph[v]:
            indeg[w] += 1                # one more arrow into w
    return indeg

dressing = {"A": ["B"], "B": ["D"], "C": ["D"], "D": [], "E": ["F"], "F": []}
print(sorted(in_degrees(dressing).items()))
print([v for v in sorted(dressing) if in_degrees(dressing)[v] == 0])   # the sources

def is_valid_order(order, edges):
    place = {v: i for i, v in enumerate(order)}     # where each job sits in the order
    return all(place[a] < place[b] for a, b in edges)

arrows = [("A", "B"), ("B", "D"), ("C", "D"), ("E", "F")]
print(is_valid_order(["C", "E", "A", "B", "F", "D"], arrows))
print(is_valid_order(["A", "D", "B", "C", "E", "F"], arrows))   # shoes before trousers

Mistakes and edge cases.

  • reading an arrow the wrong way: decide once what a → b means (here: a before b) and keep to it, or the whole order comes out reversed
  • forgetting vertices with no arrows in: a vertex nothing points to must still appear in the in-degree table, with 0
  • expecting one answer: a DAG can have many topological orders; check any proposed one against the arrows instead of comparing it with a single "right" list
  • a cycle: no order exists at all; an algorithm that assumes a DAG must notice a cycle instead of returning a wrong order (Lesson 52.4)
  • a self-loop a → a: that is a cycle of length one

Quiz

  1. What does this print?

    def in_degrees(graph):
        indeg = {v: 0 for v in graph}        # every vertex, even one nothing points to
        for v in graph:
            for w in graph[v]:
                indeg[w] += 1                # one more arrow into w
        return indeg
    
    print(sorted(in_degrees({"A": ["C"], "B": ["C", "D"], "C": ["E"], "D": ["E"], "E": ["F"], "F": []}).items()))
  2. Which of these graphs has no topological order?

    • A → B, B → C, C → A
    • A → B, A → C, B → C
    • A → B, C → D
  3. Are these valid orders for getting dressed?

    def is_valid_order(order, edges):
        place = {v: i for i, v in enumerate(order)}     # where each job sits in the order
        return all(place[a] < place[b] for a, b in edges)
    
    arrows = [("A", "B"), ("B", "D"), ("C", "D"), ("E", "F")]
    print(is_valid_order(["E", "C", "A", "F", "B", "D"], arrows), is_valid_order(["A", "B", "D", "C", "E", "F"], arrows))
  4. Why must every DAG have at least one vertex with in-degree 0?

    • Walking backwards along arrows can never repeat a vertex, so it must stop somewhere nothing points to
    • Because the vertices are sorted
    • It doesn't have to
  5. in_degrees should list every vertex, but it stops with a KeyError. Which line is wrong?

    def in_degrees(graph):
        indeg = {}
        for v in graph:
            for w in graph[v]:
                indeg[w] += 1
        return indeg

Coding tasks

  1. Write is_valid_order(order, edges): order lists every job once; edges is a list of pairs (a, b) meaning a must come before b. Return True if the order keeps every pair, otherwise False.

  2. Write in_degrees(graph): graph maps each vertex to the list of vertices that must come after it (every vertex is a key). Return a dict from every vertex to how many arrows point into it.