- Related Questions & Answers
- Program to find longest path between two nodes of a tree in Python
- Program to find length of longest path with even sum in Python
- Program to find length of longest alternating path of a binary tree in python
- Program to find length of longest consecutive path of a binary tree in python
- Program to length of longest increasing path in a given matrix in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest consecutive sequence in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic substring in Python
- Program to find length of longest possible stick in Python?
- Program to find length of longest palindromic subsequence in Python
- Program to find longest even value path of a binary tree in Python
- Find length of the longest consecutive path from a given starting characters in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

- ans := 0
- n := node count of graph
- table := a list of size n and fill with -1
- Define a function dfs() . This will take u
- if table[u] is not -1, then
- return table[u]

- p_len := 0
- for each vectex v in graph[u], do
- p_len := maximum of p_len and (1 + dfs(v))

- table[u] := p_len
- return p_len
- From the main method do the following −
- for i in range 0 to n, do
- ans := maximum of ans, dfs(i)

- return ans

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], [], [4], [2], ] print(ob.solve(graph))

graph = [[1, 2],[3, 4],[],[4],[2]]

4

Advertisements