Longest Path in a DAG
Master this topic with zero to advance depth.
Longest Path in a DAG
Given a Directed Acyclic Graph (DAG) and a source vertex src, find the distance to the farthest vertex from src.
In a general graph, finding the longest path is NP-hard. However, in a DAG, it can be solved in linear time using Topological Sort.
Visual Representation
Nodes: 0 to 5
Edges: (0,1,5), (0,2,3), (1,3,6), (1,2,2), (2,4,4), (2,5,2), (2,3,7), (3,4,-1), (4,5,-2)
Topological Order: 0, 1, 2, 3, 4, 5
Relax edges in this order to find max distances.Examples
Distances from node 1: to 3 is 9 (1->2->3 is 2+7), to 4 is 8, etc.
Level I: Brute Force (Recursion + Memoization)
Intuition
The longest path from a node u is max(weight(u, v) + longestPath(v)) for all neighbors v. Since the graph is a DAG, we can use memoization to avoid redundant computations.
Thought Process
- Define
dfs(u)as the longest path starting from nodeu. - In
dfs(u):- If
uis already inmemo, returnmemo[u]. - Initialize
max_dist = 0(or some base case). - For each neighbor
vwith weightw:max_dist = max(max_dist, w + dfs(v)).
- Store and return
max_dist.
- If
Complexity
- Time:
- Space:
Detailed Dry Run
src=1. Edges from 1: (3,6), (2,2).
- dfs(3): edge (4,-1). dfs(4): edge (5,-2). dfs(5): 0.
- dfs(4) = -1 + 0 = -1.
- dfs(3) = -1 + -1 = -2. (Wait, let's say base case is 0 for sink).
- dfs(1) = max(6 + dfs(3), 2 + dfs(2))...
Level III: Optimal (Topological Sort + Relaxation)
Intuition
Processing nodes in topological order allows finding the longest path in .
Pattern: DAG Relaxation
Detailed Dry Run
Order: 0,1,2,3,4,5. Relax edges from 1. 1->2->3 is longer than 1->3 directly.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.