14/32
Part 4 of 7 · Depth firstLearn and do

The depth-first version

Kahn's algorithm is one way to order the tasks. A depth-first search gives an order too, read off the moment each task finishes.

With no cycle, the depth-first finish order, reversed, is a build order

NEW, ACTIVE, DONE = 0, 1, 2


def dfs_order(tasks, needs):
    unblocks, _ = build_graph(tasks, needs)
    state = dict.fromkeys(tasks, NEW)
    finished = []

    def visit(task):
        state[task] = ACTIVE
        for nxt in unblocks[task]:
            if state[nxt] == ACTIVE:
                raise ValueError(f"cycle through {nxt}")
            if state[nxt] == NEW:
                visit(nxt)
        state[task] = DONE
        finished.append(task)

    for task in tasks:
        if state[task] == NEW:
            visit(task)
    return finished[::-1]


print(dfs_order(tasks, needs))
Predict

dfs_order starts at fetch and follows unblocks as deep as it goes. Which task finishes first?

Pick one to see what it prints.
Pick an answer above to see the rest