Suppose we have one directed acyclic graph represented by the adjacency list. We have to find the longest path in the graph without node repetition.
So, if the input is like
then the output will be 4, as the path is 0 -> 1 -> 3 -> 4 -> 2 with length 4.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
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 ob = Solution() graph = [ [1, 2], [3, 4], , , , ] print(ob.solve(graph))
graph = [[1, 2],[3, 4],,,]