Graph Theory37 sections · 1633 units
Open in Course

The DP on DAGs Pattern

Process in topological order

Finding the longest path in a general graph is NP-hard.

But in a DAG, it is easy with DP. Idea: Process nodes in topological order. For each node vv, dp[v] stores the longest path ending at vv. For each edge u→vu \to v, update dp[v] = max(dp[v], dp[u] + 1). Start with dp[source] = 0, all others at −∞-\infty. Answer is dp[destination]. Shortest path works the same way, use min⁡\min instead of max⁡\max.