A dependency graph tells you what can happen next
Picture
Some edges mean “travel here.” Others mean “finish this before that.” For prerequisites, a node becomes ready when every incoming dependency is satisfied. A topological ordering lists a directed acyclic graph so that each prerequisite appears before its dependent.
Predict
Tasks A and B both require each other to finish first. Can choosing a different first task resolve the problem?
Reveal the reasoning
No. There is no valid first task under those rules. A directed cycle prevents a topological ordering; it is a dependency problem, not an unfortunate queue order.
Go deeper: readiness is an invariant
Assume nodes are 0..n-1 and each input edge (u, v) means u must precede v.
from collections import deque
def order_tasks(n, edges):
graph = [[] for _ in range(n)]
incoming = [0] * n
for u, v in edges:
graph[u].append(v)
incoming[v] += 1
ready = deque(i for i in range(n) if incoming[i] == 0)
order = []
while ready:
u = ready.popleft()
order.append(u)
for v in graph[u]:
incoming[v] -= 1
if incoming[v] == 0:
ready.append(v)
return order if len(order) == n else None
assert order_tasks(3, [(0, 2), (1, 2)]) == [0, 1, 2]
assert order_tasks(2, [(0, 1), (1, 0)]) is None
assert order_tasks(0, []) == []
The queue contains tasks whose remaining incoming count is zero. Processing a task removes its obligation from each dependent. If tasks remain but nothing is ready, the remaining graph contains a cycle.
Time and storage are O(V+E). Multiple valid orders can exist. This queue is about dependency readiness, not shortest travel distance; using a queue alone does not make the algorithm a shortest-path BFS.
For a DP, an edge from a smaller subproblem to a larger one means “this answer must be ready first.” Recursive calls often draw arrows in the opposite direction, from caller to dependency. Always state your arrow convention.
Analogy limit: tasks with mutually recursive equations may still have solutions through other techniques. They simply cannot be evaluated by this unchanged one-pass prerequisite scheme.
Change one rule
Each task has a duration, and unlimited workers can run ready tasks simultaneously. Is a topological ordering itself the minimum completion time?
Check the variation
No. It supplies an evaluation order. Compute each task’s earliest finish as its duration plus the maximum earliest finish among its prerequisites. That adds a DP on the DAG.
Connect
Tabulation is evaluation in dependency order. Grid DP gets an order from movement restrictions. Weighted intervals builds dependencies between compatible choices.