# Longest path in a directed Acyclic graph | Dynamic Programming

Given a directed graph G with N vertices and M edges. The task is to find the length of the longest directed path in Graph.

Note: Length of a directed path is the number of edges in it.

Examples:

Input: N = 4, M = 5

Output: 3
The directed path 1->3->2->4

Input: N = 5, M = 8

Output: 3

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Simple Approach: A naive approach is to calculate the length of the longest path from every node using DFS.

The time complexity of this approach is O(N2).

Efficient Approach: An efficient approach is to use Dynamic Programming and DFS together to find the longest path in the Graph.

Let dp[i] be the length of the longest path starting from the node i. Initially all positions of dp will be 0. We can call the DFS function from every node and traverse for all its children. The recursive formula will be:

dp[node] = max(dp[node], 1 + max(dp[child1], dp[child2], dp[child3]..))

At the end check for the maximum value in dp[] array, which will be the longest path in the DAG.

Below is the implementation of the above approach:

## C#

Output:

3

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.