How to recognise
tasks with dependencies, such as prerequisites, a build order or "a must come before b", or a cycle check in a directed graph.
How to solve problems like this
- Draw an arrow from each task to the tasks that depend on it. Count each node's in-degree: the arrows coming in.
- Queue every node with in-degree 0: nothing holds it back.
- Take from the front and add it to the order. Lower the in-degree of each node it points to, and queue those that reach 0.
- If the order ends up shorter than the number of nodes, there is a cycle and no valid order.
Where it's used
- Building programs. make and Bazel build files in an order where everything a file depends on is ready first. If the dependencies loop, make warns about a circular dependency.
- Excel. Excel recalculates cells in dependency order: first the cells others refer to, then the cells that refer to them. If formulas refer to each other in a circle, it reports a circular reference.
- Python. The standard library has graphlib.TopologicalSorter: it hands out tasks whose dependencies are all done and raises an error on a cycle.