The Wayback Machine - https://web.archive.org/web/20240819102611/https://www.geeksforgeeks.org/longest-path-in-a-directed-acyclic-graph-dynamic-programming/
Open In App

Longest path in a directed Acyclic graph | Dynamic Programming

Last Updated : 30 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 

 

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++




// C++ program to find the longest
// path in the DAG
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to traverse the DAG
// and apply Dynamic Programming
// to find the longest path
void dfs(int node, vector<int> adj[], int dp[], bool vis[])
{
    // Mark as visited
    vis[node] = true;
 
    // Traverse for all its children
    for (int i = 0; i < adj[node].size(); i++) {
 
        // If not visited
        if (!vis[adj[node][i]])
            dfs(adj[node][i], adj, dp, vis);
 
        // Store the max of the paths
        dp[node] = max(dp[node], 1 + dp[adj[node][i]]);
    }
}
 
// Function to add an edge
void addEdge(vector<int> adj[], int u, int v)
{
    adj[u].push_back(v);
}
 
// Function that returns the longest path
int findLongestPath(vector<int> adj[], int n)
{
    // Dp array
    int dp[n + 1];
    memset(dp, 0, sizeof dp);
 
    // Visited array to know if the node
    // has been visited previously or not
    bool vis[n + 1];
    memset(vis, false, sizeof vis);
 
    // Call DFS for every unvisited vertex
    for (int i = 1; i <= n; i++) {
        if (!vis[i])
            dfs(i, adj, dp, vis);
    }
 
    int ans = 0;
 
    // Traverse and find the maximum of all dp[i]
    for (int i = 1; i <= n; i++) {
        ans = max(ans, dp[i]);
    }
    return ans;
}
 
// Driver Code
int main()
{
    int n = 5;
    vector<int> adj[n + 1];
 
    // Example-1
    addEdge(adj, 1, 2);
    addEdge(adj, 1, 3);
    addEdge(adj, 3, 2);
    addEdge(adj, 2, 4);
    addEdge(adj, 3, 4);
 
    cout << findLongestPath(adj, n);
    return 0;
}


Java




// Java program to find the longest
// path in the DAG
 
import java.util.ArrayList;
 
// graph class
class Graph
{
 
    int vertices;
    ArrayList<Integer> edge[];
 
    Graph(int vertices)
    {
        this.vertices = vertices;
        edge = new ArrayList[vertices+1];
        for (int i = 0; i <= vertices; i++)
        {
            edge[i] = new ArrayList<>();
        }
    }
    void addEdge(int a,int b)
    {
        edge[a].add(b);
    }
 
    void dfs(int node, ArrayList<Integer> adj[], int dp[],
                                    boolean visited[])
    {
        // Mark as visited
        visited[node] = true;
 
        // Traverse for all its children
        for (int i = 0; i < adj[node].size(); i++)
        {
 
            // If not visited
            if (!visited[adj[node].get(i)])
                dfs(adj[node].get(i), adj, dp, visited);
 
            // Store the max of the paths
            dp[node] = Math.max(dp[node], 1 + dp[adj[node].get(i)]);
        }
    }
     
    // Function that returns the longest path
    int findLongestPath( int n)
    {
        ArrayList<Integer> adj[] = edge;
        // Dp array
        int[] dp = new int[n+1];
 
        // Visited array to know if the node
        // has been visited previously or not
        boolean[] visited = new boolean[n + 1];
 
        // Call DFS for every unvisited vertex
        for (int i = 1; i <= n; i++)
        {
            if (!visited[i])
                dfs(i, adj, dp, visited);
        }
 
        int ans = 0;
 
        // Traverse and find the maximum of all dp[i]
        for (int i = 1; i <= n; i++)
        {
            ans = Math.max(ans, dp[i]);
        }
        return ans;
    }
}
 
public class Main
{
    // Driver code
    public static void main(String[] args)
    {
        int n = 5;
        Graph graph = new Graph(n);
        // Example-1
        graph.addEdge( 1, 2);
        graph.addEdge( 1, 3);
        graph.addEdge( 3, 2);
        graph.addEdge( 2, 4);
        graph.addEdge( 3, 4);
        graph.findLongestPath(n);
        System.out.println( graph.findLongestPath( n));
 
    }
}
 
// This code is contributed by SumanSaurav


Python3




# Python3 program to find the
# longest path in the DAG
   
# Function to traverse the DAG
# and apply Dynamic Programming
# to find the longest path
def dfs(node, adj, dp, vis):
  
    # Mark as visited
    vis[node] = True
   
    # Traverse for all its children
    for i in range(0, len(adj[node])): 
   
        # If not visited
        if not vis[adj[node][i]]:
            dfs(adj[node][i], adj, dp, vis)
   
        # Store the max of the paths
        dp[node] = max(dp[node], 1 + dp[adj[node][i]])
   
# Function to add an edge
def addEdge(adj, u, v):
  
    adj[u].append(v)
   
# Function that returns the longest path
def findLongestPath(adj, n):
  
    # Dp array
    dp = [0] * (n + 1)
     
    # Visited array to know if the node
    # has been visited previously or not
    vis = [False] * (n + 1)
     
    # Call DFS for every unvisited vertex
    for i in range(1, n + 1): 
        if not vis[i]:
            dfs(i, adj, dp, vis)
      
    ans = 0
   
    # Traverse and find the maximum of all dp[i]
    for i in range(1, n + 1): 
        ans = max(ans, dp[i])
      
    return ans
  
# Driver Code
if __name__ == "__main__":
  
    n = 5
    adj = [[] for i in range(n + 1)]
   
    # Example-1
    addEdge(adj, 1, 2)
    addEdge(adj, 1, 3)
    addEdge(adj, 3, 2)
    addEdge(adj, 2, 4)
    addEdge(adj, 3, 4)
   
    print(findLongestPath(adj, n))
   
# This code is contributed by Rituraj Jain


C#




// C# program to find the longest
// path in the DAG
using System;
using System.Collections.Generic;
 
// graph class
class Graph
{
    public int vertices;
    public List<int> []edge;
 
    public Graph(int vertices)
    {
        this.vertices = vertices;
        edge = new List<int>[vertices + 1];
        for (int i = 0; i <= vertices; i++)
        {
            edge[i] = new List<int>();
        }
    }
    public void addEdge(int a, int b)
    {
        edge[a].Add(b);
    }
 
    public void dfs(int node, List<int> []adj,
                    int []dp, Boolean []visited)
    {
        // Mark as visited
        visited[node] = true;
 
        // Traverse for all its children
        for (int i = 0; i < adj[node].Count; i++)
        {
 
            // If not visited
            if (!visited[adj[node][i]])
                dfs(adj[node][i], adj, dp, visited);
 
            // Store the max of the paths
            dp[node] = Math.Max(dp[node], 1 +
                                dp[adj[node][i]]);
        }
    }
     
    // Function that returns the longest path
    public int findLongestPath( int n)
    {
        List<int> []adj = edge;
        // Dp array
        int[] dp = new int[n + 1];
 
        // Visited array to know if the node
        // has been visited previously or not
        Boolean[] visited = new Boolean[n + 1];
 
        // Call DFS for every unvisited vertex
        for (int i = 1; i <= n; i++)
        {
            if (!visited[i])
                dfs(i, adj, dp, visited);
        }
 
        int ans = 0;
 
        // Traverse and find the maximum of all dp[i]
        for (int i = 1; i <= n; i++)
        {
            ans = Math.Max(ans, dp[i]);
        }
        return ans;
    }
}
 
class GFG
{
    // Driver code
    public static void Main(String[] args)
    {
        int n = 5;
        Graph graph = new Graph(n);
        // Example-1
        graph.addEdge( 1, 2);
        graph.addEdge( 1, 3);
        graph.addEdge( 3, 2);
        graph.addEdge( 2, 4);
        graph.addEdge( 3, 4);
        graph.findLongestPath(n);
        Console.WriteLine(graph.findLongestPath(n));
    }
}
 
// This code is contributed by Princi Singh


Javascript




<script>
 
// JavaScript program to find the longest
// path in the DAG
 
// Function to traverse the DAG
// and apply Dynamic Programming
// to find the longest path
function dfs(node, adj, dp, vis)
{
    // Mark as visited
    vis[node] = true;
 
    // Traverse for all its children
    for (var i = 0; i < adj[node].length; i++) {
 
        // If not visited
        if (!vis[adj[node][i]])
            dfs(adj[node][i], adj, dp, vis);
 
        // Store the max of the paths
        dp[node] = Math.max(dp[node], 1 + dp[adj[node][i]]);
    }
}
 
// Function to add an edge
function addEdge(adj, u, v)
{
    adj[u].push(v);
}
 
// Function that returns the longest path
function findLongestPath(adj, n)
{
    // Dp array
    var dp = Array(n+1).fill(0);
 
    // Visited array to know if the node
    // has been visited previously or not
    var vis = Array(n+1).fill(false);
 
    // Call DFS for every unvisited vertex
    for (var i = 1; i <= n; i++) {
        if (!vis[i])
            dfs(i, adj, dp, vis);
    }
 
    var ans = 0;
 
    // Traverse and find the maximum of all dp[i]
    for (var i = 1; i <= n; i++) {
        ans = Math.max(ans, dp[i]);
    }
    return ans;
}
 
// Driver Code
var n = 5;
var adj = Array.from(Array(n+1), ()=>Array());
// Example-1
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 3, 2);
addEdge(adj, 2, 4);
addEdge(adj, 3, 4);
document.write( findLongestPath(adj, n));
 
</script>


Output: 

3

 

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

?list=PLqM7alHXFySEaZgcg7uRYJFBnYMLti-nh
 



Similar Reads

Longest Path in a Directed Acyclic Graph | Set 2
Given a Weighted Directed Acyclic Graph (DAG) and a source vertex in it, find the longest distances from source vertex to all other vertices in the given graph. We have already discussed how we can find Longest Path in Directed Acyclic Graph(DAG) in Set 1. In this post, we will discuss another interesting solution to find longest path of DAG that u
14 min read
Longest Path in a Directed Acyclic Graph
Given a Weighted Directed Acyclic Graph (DAG) and a source vertex s in it, find the longest distances from s to all other vertices in the given graph. The longest path problem for a general graph is not as easy as the shortest path problem because the longest path problem doesn’t have optimal substructure property. In fact, the Longest Path problem
15+ min read
Dynamic Programming (DP) and Directed Acyclic Graphs (DAG)
Pre-Requisite:What is Directed Graph? | Directed Graph meaningDynamic Programming (DP) Tutorial with Problems Every Dynamic Programming problem can be represented as a Directed Acyclic Graph(DAG). The nodes of the DAG represent the subproblems and the edges represents the transitions between the subproblems. Table of Content Relationship Between Dy
15+ min read
Shortest Path in Directed Acyclic Graph
Given a Weighted Directed Acyclic Graph and a source vertex in the graph, find the shortest paths from given source to all other vertices. Recommended PracticeShortest path from 1 to nTry It! For a general weighted graph, we can calculate single source shortest distances in O(VE) time using Bellman–Ford Algorithm. For a graph with no negative weigh
15 min read
What is Directed Graph? | Directed Graph meaning
A directed graph is defined as a type of graph where the edges have a direction associated with them. Characteristics of Directed Graph Directed graphs have several characteristics that make them different from undirected graphs. Here are some key characteristics of directed graphs: Directed edges: In a directed graph, edges have a direction associ
3 min read
Assign directions to edges so that the directed graph remains acyclic
Given a graph with both directed and undirected edges. It is given that the directed edges don't form cycle. How to assign directions to undirected edges so that the graph (with all directed edges) remains acyclic even after the assignment? For example, in the below graph, blue edges don't have directions. We strongly recommend to minimize your bro
1 min read
Number of paths from source to destination in a directed acyclic graph
Given a Directed Acyclic Graph with n vertices and m edges. The task is to find the number of different paths that exist from a source vertex to destination vertex. Examples: Input: source = 0, destination = 4 Output: 3 Explanation: 0 -&gt; 2 -&gt; 3 -&gt; 4 0 -&gt; 3 -&gt; 4 0 -&gt; 4 Input: source = 0, destination = 1 Output: 1 Explanation: There
15+ min read
Maximum difference between node and its ancestor in a Directed Acyclic Graph ( DAG )
Given a 2D array Edges[][], representing a directed edge between the pair of nodes in a Directed Acyclic Connected Graph consisting of N nodes valued from [1, N] and an array arr[] representing weights of each node, the task is to find the maximum absolute difference between the weights of any node and any of its ancestors. Examples: Input: N = 5,
8 min read
Count nodes with prime weight in a Directed Acyclic Graph
Given a directed acyclic graph (DAG) with N nodes with integer representations 0 to N-1 and an integer array arr[], where arr[i] is the parent of node i. The root of the DAG is node i if arr[i] is 0. The weight of a node is calculated as the sum of the node's value and the number of parent nodes it has, the task is to determine the number of nodes,
8 min read
Introduction to Directed Acyclic Graph
A Directed Acyclic Graph, often abbreviated as DAG, is a fundamental concept in graph theory. DAGs are used to show how things are related or depend on each other in a clear and organized way. In this article, we are going to learn about Directed Acyclic Graph, its properties, and application in real life. What is Directed Acyclic Graph?A Directed
3 min read
All Topological Sorts of a Directed Acyclic Graph
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG. Given a DAG, print all topological sorts of the graph. For example, consider the below graph. All topological
11 min read
Clone a Directed Acyclic Graph
A directed acyclic graph (DAG) is a graph which doesn't contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them. Examples: Input : 0 - - - &gt; 1 - - - -&gt; 4 | / \ ^ | / \ | | / \ | | / \ | | / \ | | / \ | v v v | 2 - - - - - - - - -&gt; 3
12 min read
Minimum time taken by each job to be completed given by a Directed Acyclic Graph
Given a Directed Acyclic Graph having V vertices and E edges, where each edge {U, V} represents the Jobs U and V such that Job V can only be started only after completion of Job U. The task is to determine the minimum time taken by each job to be completed where each Job takes unit time to get completed.Examples: Input: N = 10, E = 13, Below is the
12 min read
Find the Dominators for every vertex in a given DAG (Directed Acyclic Graph)
Given a Directed Acyclic Graph with V vertices and E edges, the task is to find the set of dominant vertices for each vertex of the graph. What are Dominators in Graph Theory: In control flow graphs a vertex V1 is the dominator of another vertex V2 if all the paths from the source vertex (in this case the vertex ‘0’) to the vertex V2 passes through
9 min read
Convert the undirected graph into directed graph such that there is no path of length greater than 1
Given an undirected graph with N vertices and M edges and no self loops or multiple edges. The task is to convert the given undirected graph into a directed graph such that there is no path of length greater than 1. If it is possible to make such a graph then print two space-separated integers u and v in M lines where u, v denotes source and destin
10 min read
Find if there is a path between two vertices in a directed graph
Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second. Example: Consider the following Graph: Input : (u, v) = (1, 3) Output: Yes Explanation: There is a path from 1 to 3, 1 -&gt; 2 -&gt; 3 Input : (u, v) = (3, 6) Output: No Explanation: There is no path from 3 to 6 Approach: Either Bread
15 min read
Shortest path with exactly k edges in a directed and weighted graph
Given a directed and two vertices ‘u’ and ‘v’ in it, find shortest path from ‘u’ to ‘v’ with exactly k edges on the path. The graph is given as adjacency matrix representation where value of graph[i][j] indicates the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge from i to j. For example, consider the follow
15+ min read
Find if there is a path between two vertices in a directed graph | Set 2
Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second. Example: Consider the following Graph: Input : (u, v) = (1, 3) Output: Yes Explanation: There is a path from 1 to 3, 1 -&gt; 2 -&gt; 3 Input : (u, v) = (3, 6) Output: No Explanation: There is no path from 3 to 6 A BFS or DFS based sol
7 min read
Shortest path with exactly k edges in a directed and weighted graph | Set 2
Given a directed weighted graph and two vertices S and D in it, the task is to find the shortest path from S to D with exactly K edges on the path. If no such path exists, print -1. Examples: Input: N = 3, K = 2, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: 8 Explanation: The shortest path with two edges will be 1-&gt;2-&gt;3
8 min read
Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph
Given a directed graph, which may contain cycles, where every edge has weight, the task is to find the minimum cost of any simple path from a given source vertex ‘s’ to a given destination vertex ‘t’. Simple Path is the path from one vertex to another such that no vertex is visited more than once. If there is no simple path possible then return INF
10 min read
Path with minimum XOR sum of edges in a directed graph
Given a directed graph with N nodes and E edges, a source S and a destination D nodes. The task is to find the path with the minimum XOR sum of edges from S to D. If there is no path from S to D then print -1. Examples: Input: N = 3, E = 3, Edges = {{{1, 2}, 5}, {{1, 3}, 9}, {{2, 3}, 1}}, S = 1, and D = 3 Output: 4 The path with smallest XOR of edg
8 min read
Minimum Cost Path in a directed graph via given set of intermediate nodes
Given a weighted, directed graph G, an array V[] consisting of vertices, the task is to find the Minimum Cost Path passing through all the vertices of the set V, from a given source S to a destination D. Examples: Input: V = {7}, S = 0, D = 6 Output: 11 Explanation: Minimum path 0-&gt;7-&gt;5-&gt;6. Therefore, the cost of the path = 3 + 6 + 2 = 11
10 min read
Minimum cost of path between given nodes containing at most K nodes in a directed and weighted graph
Given a directed weighted graph represented by a 2-D array graph[][] of size n and 3 integers src, dst, and k representing the source point, destination point, and the available number of stops. The task is to minimize the cost of the path between two nodes containing at most K nodes in a directed and weighted graph. If there is no such route, retu
10 min read
Monotonic shortest path from source to destination in Directed Weighted Graph
Given a weighted directed graph with N vertices and M edges, a source src and a destination target, the task is to find the shortest monotonic path (monotonically increasing or decreasing) from the source to the destination. Output -1 if no monotonic path is possible. Note: All weights are non-negative Examples: Input: N = 6, M = 9, src = 1, target
14 min read
Convert undirected connected graph to strongly connected directed graph
Given an undirected graph of N vertices and M edges, the task is to assign directions to the given M Edges such that the graph becomes Strongly Connected Components. If a graph cannot be converted into Strongly Connected Components then print "-1". Examples: Input: N = 5, Edges[][] = { { 0, 1 }, { 0, 2 }, { 1, 2 }, { 1, 4 }, { 2, 3 }, { 3, 4 } } Ou
14 min read
Count ways to change direction of edges such that graph becomes acyclic
Given a directed and unweighted graph consisting of N vertices and an array arr[] where ith vertex has a directed edge to arr[i]. The task is to find the number of ways to change the direction of edges such that the given graph is acyclic. Examples: Input: N = 3, arr[] = {2, 3, 1} The directed graph form by the given information is: Output: 6 Expla
12 min read
Minimum number of edges required to be removed from an Undirected Graph to make it acyclic
Given an undirected graph consisting of N nodes containing values from the range [1, N] and M edges in a matrix Edges[][], the task is to determine the minimum number of edges required to be removed such that the resulting graph does not contain any cycle. Examples: Input: N = 3, M = 3, edges[][] = [[1, 2], [2, 3], [3, 1]] Output: 1Explanation:Remo
8 min read
Calculate number of nodes between two vertices in an acyclic Graph by DFS method
Given a connected acyclic graph consisting of V vertices and E edges, a source vertex src, and a destination vertex dest, the task is to count the number of vertices between the given source and destination vertex in the graph. Examples: Input: V = 8, E = 7, src = 7, dest = 8, edges[][] ={{1 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}Output
10 min read
Count permutations of all integers upto N that can form an acyclic graph based on given conditions
Given an integer N, the task is to find the number of permutations of integers from the range [1, N] that can form an acyclic graph according to the following conditions: For every 1 ? i ? N, find the largest j such that 1 ? j &lt; i and A[j] &gt; A[i], and add an undirected edge between node i and node j.For every 1 ? i ? N, find the smallest j su
4 min read
Maximum Bitwise XOR of node values of an Acyclic Graph made up of N given vertices using M edges
Given N nodes valued by [1, N], an array arr[] consisting of N positive integers such that the ith node ( 1-based indexing ) has the value arr[i] and an integer M, the task is to find the maximum Bitwise XOR of node values of an acyclic graph formed by M edges. Examples: Input: arr[]= {1, 2, 3, 4}, M = 2Output: 7Explanation:Acyclic graphs having M(
7 min read
three90RightbarBannerImg