A directed acyclic graph (DAG) is a graph where edges point in one direction and there are no cycles — no way to follow edges and arrive back where you started. That sounds like a restriction, but it is actually a superpower.
Because there are no cycles, a DAG has a topological order: a way to list every node so that all edges point forward — from earlier entries in the list to later ones. Think of it like a schedule: task B can only start after task A finishes, and the topological order simply lists tasks in a valid execution sequence.
Once you have that order, dynamic programming becomes trivial. To compute the optimal value at any node, you only need to look at the nodes that come before it — and those have already been processed. A single left-to-right sweep over the topologically sorted nodes solves the entire problem.
This is not a niche trick. Shortest paths in a DAG, longest paths (critical path scheduling), the number of paths between two nodes, the probability of reaching a target — all collapse to the same linear scan. The key insight, proven by the structure of DAGs themselves, is that optimal substructure + topological order = one pass.
Comments
Loading comments...