Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find length of the longest path in a DAG without repeated nodes in Python
Finding the longest path in a Directed Acyclic Graph (DAG) without repeated nodes is a classic dynamic programming problem. Since the graph has no cycles, we can use memoization with depth-first search to efficiently compute the longest path from any starting node.
Problem Understanding
Given a DAG represented as an adjacency list, we need to find the length of the longest simple path (without repeated nodes). The example graph below shows nodes 0-4 with the longest path being 0 ? 1 ? 3 ? 4 ? 2 with length 4.
Algorithm Approach
We use dynamic programming with memoization where each node stores the length of the longest path starting from that node. The algorithm works as follows:
- Create a memoization table to store computed results
- For each node, recursively find the longest path from its neighbors
- Return the maximum path length among all starting nodes
Implementation
class Solution:
def solve(self, graph):
ans = 0
n = len(graph)
table = [-1] * n
def dfs(u):
if table[u] != -1:
return table[u]
p_len = 0
for v in graph[u]:
p_len = max(p_len, 1 + dfs(v))
table[u] = p_len
return p_len
for i in range(n):
ans = max(ans, dfs(i))
return ans
# Example usage
ob = Solution()
graph = [
[1, 2], # Node 0 connects to nodes 1, 2
[3, 4], # Node 1 connects to nodes 3, 4
[], # Node 2 has no outgoing edges
[4], # Node 3 connects to node 4
[2], # Node 4 connects to node 2
]
result = ob.solve(graph)
print(f"Longest path length: {result}")
Longest path length: 4
How It Works
The algorithm uses top-down dynamic programming:
-
table[u]stores the longest path starting from nodeu - For each neighbor
v, we recursively calculate1 + dfs(v) - Memoization prevents recalculating the same subproblems
- We try all nodes as starting points and return the maximum
Time Complexity
The time complexity is O(V + E) where V is the number of vertices and E is the number of edges. Each node is visited once due to memoization, and each edge is processed once.
Conclusion
This solution efficiently finds the longest path in a DAG using dynamic programming with memoization. The key insight is that in a DAG, we can safely use memoization since there are no cycles to worry about.
