
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Length of the Longest Path in a DAG Without Repeated Nodes in Python
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
Example (Python)
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))
Input
graph = [[1, 2],[3, 4],[],[4],[2]]
Output
4
Advertisements