The Wayback Machine - https://web.archive.org/web/20241123130617/https://www.geeksforgeeks.org/dynamic-programming-dp-and-directed-acyclic-graphs-dag/
Open In App

Dynamic Programming (DP) and Directed Acyclic Graphs (DAG)

Last Updated : 07 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Pre-Requisite:
What is Directed Graph? | Directed Graph meaning
Dynamic 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.

Dp-on-direct-Graph

Relationship Between Dynamic Programming (DP) and Directed Acyclic Graphs (DAG):

1. Subproblems and DAG Nodes:

  • Dynamic Programming involves breaking down a problem into similar subproblems and these subproblems are solved independently and their result is used to solve the original problem.
  • Nodes of Directed Acyclic Graph represents the subproblems. We can also say these nodes represent a state.

2. Transitions and DAG Edges:

  • Like the Nodes represents subproblems in the DAG, similarly the edges represent transition.
  • The transition from one subproblem to another is represented by an edge.

3. Cycles and Redundancy:

  • The reason it's a directed acyclic graph is that if there are cycles in the directed graph then some states would lead back to themselves after a series of transitions leading to redundancy.

Let's take an example to understand the above points:

Problem: Finding Longest Path in Directed Acyclic Graphs (DAG):

The dp state and the transition in this case will be:

Let dp[v] denote the length of the longest path ending at the node v. Initialize all the positions in dp array as 1. Clearly,

For every edge from node u to node v, dp[v] = max (dp[u]+1)

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

DAG
DP on Directed Graphs

What happens when the graph is not Directed Acyclic Graphs (DAG)?

If the graph contains a cycle, then some states would lead back to themselves after a series of transitions. This would lead to infinite calculations. Thus, answer will not exist if the graph is cyclic in this case. As shown in below image, we potentially keep traversing the cycle indefinitely, making it impossible to find the longest path.

DAG_Cycle
DP on Directed Graphs

How to Solve Dynamic Programming (DP) Problems on Directed Graphs:

Let us consider few problems which will tell how to define the states and make the transition:

Count the number of different ways to reach a node:

Given a Directed Acyclic Graph consisting of N nodes and M edges. The task is to determine the number of different ways to reach Node N from Node 1.

Solution: The problem can be solved in following steps:

1. Define the States: As mentioned above each Nodes of Directed Acyclic Graph represents a state. Let dp[v] be the number of ways to reach Node N from the vertex v.

2. Make the Transitions: Like the Nodes represents states in the DAG, similarly the edges represent transition. Thus dp[v] can be calculated by:

dp[v] = Σdp[u], for every edge v->u

3. Topological Consideration: We process the nodes topologically i.e., if edge v->u exists then dp[u] should be computed before dp[v].

Hence ,dp[1] will be our final answer.

Below is the implementation of above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Recursive function to perform depth-first search
// and calculate the number of ways to reach Node N from
// vertex curr
int dfs(int n, vector<vector<int> >& adj, vector<int>& dp,
        vector<int>& vis, int curr)
{
    // If the node has already been visited, return its
    // stored value
    if (vis[curr] == 1)
        return dp[curr];

    // Mark the current node as visited
    vis[curr] = 1;

    // Traverse all adjacent nodes and recursively calculate
    // the number of ways
    for (auto x : adj[curr]) {
        if (!vis[x]) {
            dfs(n, adj, dp, vis, x);
        }

        // Update the number of ways to reach Node N from
        // the current node
        dp[curr] += dp[x];
    }

    // Return the calculated value for the current node
    return dp[curr];
}

// Function to calculate the number of ways to reach Node N
// from Node 1
int noOfWays(int n, vector<vector<int> >& edges)
{
    // Adjacency list to represent the directed acyclic
    // graph
    vector<vector<int> > adj(n + 1);

    // Populate the adjacency list using the provided edges
    for (vector<int> i : edges) {
        adj[i[0]].push_back(i[1]);
    }

    // Initialize dp array to store the number of ways to
    // reach Node N from each vertex
    vector<int> dp(n + 1, 0);

    // Initialize visited array to keep track of visited
    // nodes during DFS
    vector<int> vis(n + 1, 0);

    // Set the base case for Node N, i.e., there is one way
    // to reach N from N
    dp[n] = 1;

    // Mark Node N as visited
    vis[n] = 1;

    // Call the recursive DFS function to calculate the
    // number of ways
    int res = dfs(n, adj, dp, vis, 1);

    // Return the result, which represents the number of
    // ways to reach Node N from Node 1
    return res;
}

int main()
{
    // Example inputs
    int N = 5;
    vector<vector<int> > edges = {
        { 1, 2 }, { 1, 3 }, { 2, 4 }, { 3, 4 }, { 4, 5 }
    };

    // Function call
    int result = noOfWays(N, edges);

    // Output the result
    cout << "No. of ways to reach Node N from Node 1: "
         << result << endl;

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class WaysToReachNodeN {

    // Recursive function to perform depth-first search
    // and calculate the number of ways to reach Node N from
    // vertex curr
    private static int dfs(int n, List<List<Integer>> adj, int[] dp,
                           int[] vis, int curr) {
        // If the node has already been visited, return its
        // stored value
        if (vis[curr] == 1)
            return dp[curr];

        // Mark the current node as visited
        vis[curr] = 1;

        // Traverse all adjacent nodes and recursively calculate
        // the number of ways
        for (int x : adj.get(curr)) {
            if (vis[x] == 0) {
                dfs(n, adj, dp, vis, x);
            }

            // Update the number of ways to reach Node N from
            // the current node
            dp[curr] += dp[x];
        }

        // Return the calculated value for the current node
        return dp[curr];
    }

    // Function to calculate the number of ways to reach Node N
    // from Node 1
    private static int noOfWays(int n, List<List<Integer>> edges) {
        // Adjacency list to represent the directed acyclic
        // graph
        List<List<Integer>> adj = new ArrayList<>(n + 1);

        // Populate the adjacency list using the provided edges
        for (int i = 0; i <= n; i++) {
            adj.add(new ArrayList<>());
        }

        for (List<Integer> edge : edges) {
            adj.get(edge.get(0)).add(edge.get(1));
        }

        // Initialize dp array to store the number of ways to
        // reach Node N from each vertex
        int[] dp = new int[n + 1];

        // Initialize visited array to keep track of visited
        // nodes during DFS
        int[] vis = new int[n + 1];

        // Set the base case for Node N, i.e., there is one way
        // to reach N from N
        dp[n] = 1;

        // Mark Node N as visited
        vis[n] = 1;

        // Call the recursive DFS function to calculate the
        // number of ways
        int res = dfs(n, adj, dp, vis, 1);

        // Return the result, which represents the number of
        // ways to reach Node N from Node 1
        return res;
    }

    public static void main(String[] args) {
        // Example inputs
        int N = 5;
        List<List<Integer>> edges = List.of(
                List.of(1, 2), List.of(1, 3), List.of(2, 4), List.of(3, 4), List.of(4, 5)
        );

        // Function call
        int result = noOfWays(N, edges);

        // Output the result
        System.out.println("No. of ways to reach Node N from Node 1: " + result);
    }
}
C#
using System;
using System.Collections.Generic;

class Program
{
    // Recursive function to perform depth-first search
    // and calculate the number of ways to reach Node N from
    // vertex curr
    static int DFS(int n, List<List<int>> adj, List<int> dp,
                   List<int> vis, int curr)
    {
        // If the node has already been visited, return its
        // stored value
        if (vis[curr] == 1)
            return dp[curr];

        // Mark the current node as visited
        vis[curr] = 1;

        // Traverse all adjacent nodes and recursively calculate
        // the number of ways
        foreach (int x in adj[curr])
        {
            if (vis[x] == 0)
                DFS(n, adj, dp, vis, x);

            // Update the number of ways to reach Node N from
            // the current node
            dp[curr] += dp[x];
        }

        // Return the calculated value for the current node
        return dp[curr];
    }

    // Function to calculate the number of ways to reach Node N
    // from Node 1
    static int NoOfWays(int n, List<List<int>> edges)
    {
        // Adjacency list to represent the directed acyclic
        // graph
        List<List<int>> adj = new List<List<int>>(n + 1);

        // Initialize adjacency list
        for (int i = 0; i <= n; i++)
        {
            adj.Add(new List<int>());
        }

        // Populate the adjacency list using the provided edges
        foreach (List<int> i in edges)
        {
            adj[i[0]].Add(i[1]);
        }

        // Initialize dp array to store the number of ways to
        // reach Node N from each vertex
        List<int> dp = new List<int>(new int[n + 1]);

        // Initialize visited array to keep track of visited
        // nodes during DFS
        List<int> vis = new List<int>(new int[n + 1]);

        // Set the base case for Node N, i.e., there is one way
        // to reach N from N
        dp[n] = 1;

        // Mark Node N as visited
        vis[n] = 1;

        // Call the recursive DFS function to calculate the
        // number of ways
        int res = DFS(n, adj, dp, vis, 1);

        // Return the result, which represents the number of
        // ways to reach Node N from Node 1
        return res;
    }

    static void Main()
    {
        // Example inputs
        int N = 5;
        List<List<int>> edges = new List<List<int>>
        {
            new List<int> {1, 2},
            new List<int> {1, 3},
            new List<int> {2, 4},
            new List<int> {3, 4},
            new List<int> {4, 5}
        };

        // Function call
        int result = NoOfWays(N, edges);

        // Output the result
        Console.WriteLine($"No. of ways to reach Node N from Node 1: {result}");
    }
}
JavaScript
// Function to perform depth-first search
// and calculate the number of ways to reach Node N from vertex curr
function dfs(n, adj, dp, vis, curr) {
    // If the node has already been visited, return its stored value
    if (vis[curr] === 1)
        return dp[curr];

    // Mark the current node as visited
    vis[curr] = 1;

    // Traverse all adjacent nodes and recursively calculate the number of ways
    for (let x of adj[curr]) {
        if (vis[x] === 0) {
            dfs(n, adj, dp, vis, x);
        }

        // Update the number of ways to reach Node N from the current node
        dp[curr] += dp[x];
    }

    // Return the calculated value for the current node
    return dp[curr];
}

// Function to calculate the number of ways to reach Node N from Node 1
function noOfWays(n, edges) {
    // Adjacency list to represent the directed acyclic graph
    let adj = new Array(n + 1).fill().map(() => []);

    // Populate the adjacency list using the provided edges
    for (let edge of edges) {
        adj[edge[0]].push(edge[1]);
    }

    // Initialize dp array to store the number of ways to reach Node N from each vertex
    let dp = new Array(n + 1).fill(0);

    // Initialize visited array to keep track of visited nodes during DFS
    let vis = new Array(n + 1).fill(0);

    // Set the base case for Node N, i.e., there is one way to reach N from N
    dp[n] = 1;

    // Mark Node N as visited
    vis[n] = 1;

    // Call the recursive DFS function to calculate the number of ways
    let res = dfs(n, adj, dp, vis, 1);

    // Return the result, which represents the number of ways to reach Node N from Node 1
    return res;
}

// Example inputs
let N = 5;
let edges = [
    [1, 2], [1, 3], [2, 4], [3, 4], [4, 5]
];

// Function call
let result = noOfWays(N, edges);

// Output the result
console.log("No. of ways to reach Node N from Node 1:", result);
Python3
from collections import defaultdict

def dfs(n, adj, dp, vis, curr):
    # If the node has already been visited, return its stored value
    if vis[curr] == 1:
        return dp[curr]

    # Mark the current node as visited
    vis[curr] = 1

    # Traverse all adjacent nodes and recursively calculate the number of ways
    for x in adj[curr]:
        if vis[x] == 0:
            dfs(n, adj, dp, vis, x)

        # Update the number of ways to reach Node N from the current node
        dp[curr] += dp[x]

    # Return the calculated value for the current node
    return dp[curr]

def no_of_ways(n, edges):
    # Adjacency list to represent the directed acyclic graph
    adj = defaultdict(list)

    # Populate the adjacency list using the provided edges
    for edge in edges:
        adj[edge[0]].append(edge[1])

    # Initialize dp array to store the number of ways to reach Node N from each vertex
    dp = [0] * (n + 1)

    # Initialize visited array to keep track of visited nodes during DFS
    vis = [0] * (n + 1)

    # Set the base case for Node N, i.e., there is one way to reach N from N
    dp[n] = 1

    # Mark Node N as visited
    vis[n] = 1

    # Call the recursive DFS function to calculate the number of ways
    res = dfs(n, adj, dp, vis, 1)

    # Return the result, which represents the number of ways to reach Node N from Node 1
    return res

# Example inputs
N = 5
edges = [
    (1, 2), (1, 3), (2, 4), (3, 4), (4, 5)
]

# Function call
result = no_of_ways(N, edges)

# Output the result
print("No. of ways to reach Node N from Node 1:", result)

Output
No. of ways to reach Node N from Node 1: 2

Time Complexity: O(N), Where ‘N’ is the number of nodes in the given graph.
Auxiliary Space: O(N)

Find the largest number of nodes colored with the most occurring color on any path of DAG:

Given a Directed Acyclic Graph consisting of N nodes and M edges. Each node is assigned a lowercase alphabet representing the color of that node ('a' to 'z'). The task is to determine the largest value of any path. The value of a path is defined as the number of nodes which are colored with the most occurring color in the path.

Solution: The problem can be solved in following steps:

1. Define the States: We can observe that there are total 26 colors possible. So, we can make a 2D dp[][] array of size N*26. Let dp[v][i] represent the maximum count of vertices having color i of any path starting from vertex v.

2. Make the Transitions: Again, like the Nodes represent states in the DAG, similarly the edges represent transitions. Thus dp[v][i] can be calculated by:

dp[v][i] = max(dp[u][i]+col, dp[v][i]), for each edge v->u and each color i from 0 to 25. The value of col will be 1 if color of vertex v is equal to i otherwise it will be 0.

3. Topological Consideration: Again, we process the nodes topologically i.e., if edge v->u exists then the node u should be processed before node v.

Hence, our final answer will be maximum of dp[v][i] for each vertex from 1 to N and color from 0 to 25.

Below is the implementation of above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Recursive function to perform depth-first search
// and calculate the maximum count of vertices having a specific color
void dfs(int n, vector<vector<int>>& adj, vector<vector<int>>& dp,
         vector<int>& vis, int curr, string& s) {
    // If the node has already been visited, return
    if (vis[curr] == 1)
        return;

    // Mark the current node as visited
    vis[curr] = 1;

    // Initialize the color count for the current node
    dp[curr][s[curr - 1] - 97] = 1;

    // Traverse all adjacent nodes and recursively calculate
    // the maximum count of vertices having each color
    for (auto x : adj[curr]) {
        if (!vis[x]) {
            dfs(n, adj, dp, vis, x, s);
        }

        // Update the count of vertices having each color
        for (int j = 0; j < 26; j++) {
            int col = 0;
            if (s[curr - 1] - 97 == j)
                col = 1;
            dp[curr][j] = max(dp[curr][j], dp[x][j] + col);
        }
    }
}

// Function to calculate the maximum count of vertices
// having the most occurring color in any path
int maxcolorpath(int n, vector<vector<int>>& edges, string s) {
    // Adjacency list to represent the directed acyclic graph
    vector<vector<int>> adj(n + 1);

    // Populate the adjacency list using the provided edges
    for (vector<int> i : edges) {
        adj[i[0]].push_back(i[1]);
    }

    // Initialize dp array to store the maximum count of vertices
    // having each color for each vertex
    vector<vector<int>> dp(n + 1, vector<int>(26, 0));

    // Initialize visited array to keep track of visited nodes during DFS
    vector<int> vis(n + 1);

    // Call the recursive DFS function to calculate the maximum count
    dfs(n, adj, dp, vis, 1, s);

    // Find the maximum count of vertices having the most occurring color
    int res = 0;
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < 26; j++) {
            res = max(res, dp[i][j]);
        }
    }
    return res;
}

int main() {
    // Example inputs
    int N = 5;
    vector<vector<int>> edges = {
        {1, 2}, {1, 3}, {2, 4}, {3, 4}, {4, 5}
    };
    string color = "abaca";

    // Function call
    int result = maxcolorpath(N, edges, color);

    // Output the result
    cout << "Maximum count of vertices having the most occurring color: "
         << result << endl;

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;

public class MaxColorPath {

    // Recursive function to perform depth-first search
    // and calculate the maximum count of vertices having a specific color
    static void dfs(int n, ArrayList<ArrayList<Integer>> adj, int[][] dp,
                    int[] vis, int curr, String s) {
        // If the node has already been visited, return
        if (vis[curr] == 1)
            return;

        // Mark the current node as visited
        vis[curr] = 1;

        // Initialize the color count for the current node
        dp[curr][s.charAt(curr - 1) - 'a'] = 1;

        // Traverse all adjacent nodes and recursively calculate
        // the maximum count of vertices having each color
        for (int x : adj.get(curr)) {
            if (vis[x] == 0) {
                dfs(n, adj, dp, vis, x, s);
            }

            // Update the count of vertices having each color
            for (int j = 0; j < 26; j++) {
                int col = (s.charAt(curr - 1) - 'a' == j) ? 1 : 0;
                dp[curr][j] = Math.max(dp[curr][j], dp[x][j] + col);
            }
        }
    }

    // Function to calculate the maximum count of vertices
    // having the most occurring color in any path
    static int maxColorPath(int n, int[][] edges, String s) {
        // Adjacency list to represent the directed acyclic graph
        ArrayList<ArrayList<Integer>> adj = new ArrayList<>(n + 1);

        for (int i = 0; i <= n; i++) {
            adj.add(new ArrayList<>());
        }

        // Populate the adjacency list using the provided edges
        for (int[] edge : edges) {
            adj.get(edge[0]).add(edge[1]);
        }

        // Initialize dp array to store the maximum count of vertices
        // having each color for each vertex
        int[][] dp = new int[n + 1][26];

        // Initialize visited array to keep track of visited nodes during DFS
        int[] vis = new int[n + 1];

        // Call the recursive DFS function to calculate the maximum count
        dfs(n, adj, dp, vis, 1, s);

        // Find the maximum count of vertices having the most occurring color
        int res = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < 26; j++) {
                res = Math.max(res, dp[i][j]);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        // Example inputs
        int N = 5;
        int[][] edges = {
                {1, 2}, {1, 3}, {2, 4}, {3, 4}, {4, 5}
        };
        String color = "abaca";

        // Function call
        int result = maxColorPath(N, edges, color);

        // Output the result
        System.out.println("Maximum count of vertices having the most occurring color: " + result);
    }
}
C#
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    // Recursive function to perform depth-first search
    // and calculate the maximum count of vertices having a specific color
    static void Dfs(int n, List<int>[] adj, int[][] dp, int[] vis, int curr, string s)
    {
        // If the node has already been visited, return
        if (vis[curr] == 1)
            return;

        // Mark the current node as visited
        vis[curr] = 1;

        // Initialize the color count for the current node
        dp[curr][s[curr - 1] - 97] = 1;

        // Traverse all adjacent nodes and recursively calculate
        // the maximum count of vertices having each color
        foreach (var x in adj[curr])
        {
            if (vis[x] == 0)
            {
                Dfs(n, adj, dp, vis, x, s);
            }

            // Update the count of vertices having each color
            for (int j = 0; j < 26; j++)
            {
                int col = 0;
                if (s[curr - 1] - 97 == j)
                    col = 1;
                dp[curr][j] = Math.Max(dp[curr][j], dp[x][j] + col);
            }
        }
    }

    // Function to calculate the maximum count of vertices
    // having the most occurring color in any path
    static int MaxColorPath(int n, int[][] edges, string s)
    {
        // Adjacency list to represent the directed acyclic graph
        var adj = new List<int>[n + 1];
        for (int i = 0; i < adj.Length; i++)
        {
            adj[i] = new List<int>();
        }

        // Populate the adjacency list using the provided edges
        foreach (var i in edges)
        {
            adj[i[0]].Add(i[1]);
        }

        // Initialize dp array to store the maximum count of vertices
        // having each color for each vertex
        var dp = new int[n + 1][];
        for (int i = 0; i < dp.Length; i++)
        {
            dp[i] = new int[26];
        }

        // Initialize visited array to keep track of visited nodes during DFS
        var vis = new int[n + 1];

        // Call the recursive DFS function to calculate the maximum count
        Dfs(n, adj, dp, vis, 1, s);

        // Find the maximum count of vertices having the most occurring color
        int res = 0;
        for (int i = 1; i <= n; i++)
        {
            for (int j = 0; j < 26; j++)
            {
                res = Math.Max(res, dp[i][j]);
            }
        }
        return res;
    }

    static void Main()
    {
        int N = 5;
        int[][] edges = {
            new int[] {1, 2}, new int[] {1, 3}, new int[] {2, 4}, new int[] {3, 4}, new int[] {4, 5}
        };
        string color = "abaca";

        // Function call
        int result = MaxColorPath(N, edges, color);

        // Output the result
        Console.WriteLine("Maximum count of vertices having the most occurring color: "
             + result);
    }
}
JavaScript
// Recursive function to perform depth-first search
// and calculate the maximum count of vertices having a specific color
function dfs(n, adj, dp, vis, curr, s) {
    // If the node has already been visited, return
    if (vis[curr] === 1)
        return;

    // Mark the current node as visited
    vis[curr] = 1;

    // Initialize the color count for the current node
    dp[curr][s.charCodeAt(curr - 1) - 97] = 1;

    // Traverse all adjacent nodes and recursively calculate
    // the maximum count of vertices having each color
    for (let x of adj[curr]) {
        if (!vis[x]) {
            dfs(n, adj, dp, vis, x, s);
        }

        // Update the count of vertices having each color
        for (let j = 0; j < 26; j++) {
            let col = 0;
            if (s.charCodeAt(curr - 1) - 97 === j)
                col = 1;
            dp[curr][j] = Math.max(dp[curr][j], dp[x][j] + col);
        }
    }
}

// Function to calculate the maximum count of vertices
// having the most occurring color in any path
function maxcolorpath(n, edges, s) {
    // Adjacency list to represent the directed acyclic graph
    let adj = new Array(n + 1).fill(null).map(() => []);

    // Populate the adjacency list using the provided edges
    for (let i of edges) {
        adj[i[0]].push(i[1]);
    }

    // Initialize dp array to store the maximum count of vertices
    // having each color for each vertex
    let dp = new Array(n + 1).fill(null).map(() => new Array(26).fill(0));

    // Initialize visited array to keep track of visited nodes during DFS
    let vis = new Array(n + 1).fill(0);

    // Call the recursive DFS function to calculate the maximum count
    dfs(n, adj, dp, vis, 1, s);

    // Find the maximum count of vertices having the most occurring color
    let res = 0;
    for (let i = 1; i <= n; i++) {
        for (let j = 0; j < 26; j++) {
            res = Math.max(res, dp[i][j]);
        }
    }
    return res;
}

// Example inputs
let N = 5;
let edges = [
    [1, 2], [1, 3], [2, 4], [3, 4], [4, 5]
];
let color = "abaca";

// Function call
let result = maxcolorpath(N, edges, color);

// Output the result
console.log("Maximum count of vertices having the most occurring color: " + result);
//this code is contributed by Adarsh.
Python3
# Recursive function to perform depth-first search
# and calculate the maximum count of vertices having a specific color
def dfs(n, adj, dp, vis, curr, s):
    # If the node has already been visited, return
    if vis[curr] == 1:
        return

    # Mark the current node as visited
    vis[curr] = 1

    # Initialize the color count for the current node
    dp[curr][ord(s[curr - 1]) - 97] = 1

    # Traverse all adjacent nodes and recursively calculate
    # the maximum count of vertices having each color
    for x in adj[curr]:
        if not vis[x]:
            dfs(n, adj, dp, vis, x, s)

        # Update the count of vertices having each color
        for j in range(26):
            col = 0
            if ord(s[curr - 1]) - 97 == j:
                col = 1
            dp[curr][j] = max(dp[curr][j], dp[x][j] + col)

# Function to calculate the maximum count of vertices
# having the most occurring color in any path
def maxcolorpath(n, edges, s):
    # Adjacency list to represent the directed acyclic graph
    adj = [[] for _ in range(n + 1)]

    # Populate the adjacency list using the provided edges
    for i in edges:
        adj[i[0]].append(i[1])

    # Initialize dp array to store the maximum count of vertices
    # having each color for each vertex
    dp = [[0] * 26 for _ in range(n + 1)]

    # Initialize visited array to keep track of visited nodes during DFS
    vis = [0] * (n + 1)

    # Call the recursive DFS function to calculate the maximum count
    dfs(n, adj, dp, vis, 1, s)

    # Find the maximum count of vertices having the most occurring color
    res = 0
    for i in range(1, n + 1):
        for j in range(26):
            res = max(res, dp[i][j])
    return res

# Example inputs
N = 5
edges = [
    [1, 2], [1, 3], [2, 4], [3, 4], [4, 5]
]
color = "abaca"

# Function call
result = maxcolorpath(N, edges, color)

# Output the result
print("Maximum count of vertices having the most occurring color:", result)
# This code is contributed by prachi

Output
Maximum count of vertices having the most occurring color: 3

Time Complexity: O(N), Where ‘N’ is the number of nodes in the given graph.
Auxiliary Space: O(N)

Practice Problems Dynamic Programming (DP) on Directed Graphs for Competitive Programming:

Longest path in a directed Acyclic graph

Longest Path with Maximum Letter Frequency

Minimize the Maximum value

Maximum Edges In the Path

Minimum path need to reverse to reach each node in a tree from each vertex

Two-Color Sorting


Previous Article
Next Article

Similar Reads

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
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
Maximum edges that can be added to DAG so that it remains DAG
A DAG is given to us, we need to find maximum number of edges that can be added to this DAG, after which new graph still remain a DAG that means the reformed graph should have maximal number of edges, adding even single edge will create a cycle in graph. The Output for above example should be following edges in any order. 4-2, 4-5, 4-3, 5-3, 5-1, 2
14 min read
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 Simple Approach: A naive approach is to calculate the len
8 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 -> 2 -> 3 -> 4 0 -> 3 -> 4 0 -> 4 Input: source = 0, destination = 1 Output: 1 Explanation: There
15+ 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
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
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
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
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 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ | | / \ | | / \ | v v v | 2 - - - - - - - - -> 3
12 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
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
Number of Triangles in Directed and Undirected Graphs
Given a Graph, count number of triangles in it. The graph is can be directed or undirected. Example: Input: digraph[V][V] = { {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 1, 0, 0}, {0, 0, 1, 0} }; Output: 2 Give adjacency matrix represents following directed graph. We have discussed a method based on graph trace that works for undirected graphs. In this post a
10 min read
Test Case Generation | Set 4 (Random directed / undirected weighted and unweighted Graphs)
Generating Random Directed Unweighted Graphs Since this is a graph, the test data generation plan doesn't guarantee that a cycle gets formed or not.The number of edges - NUMEDGE is greater than zero and less than NUM*(NUM-1)/2, where NUM = Number of VerticesFor each RUN we first print the number of vertices - NUM first in a new separate line and th
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
Print all possible paths in a DAG from vertex whose indegree is 0
Given a Directed Acyclic Graph (DAG), having N vertices and M edges, The task is to print all path starting from vertex whose in-degree is zero. Indegree of a vertex is the total number of incoming edges to a vertex. Example: Input: N = 6, edges[] = {{5, 0}, {5, 2}, {4, 0}, {4, 1}, {2, 3}, {3, 1}} Output: All possible paths: 4 0 4 1 5 0 5 2 3 1 Exp
9 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Random Acyclic Maze Generator with given Entry and Exit point
Given two integers N and M, the task is to generate any N * M sized maze containing only 0 (representing a wall) and 1 (representing an empty space where one can move) with the entry point as P0 and exit point P1 and there is only one path between any two movable positions. Note: P0 and P1 will be marked as 2 and 3 respectively and one can move thr
15+ min read
Implement a parallel programming task using graphs
Given a weighted directed graph with N nodes and M edges along with a source node S, use Parallel Programming to find the shortest distance from the source node S to all other nodes in the graph. The graph is given as an edge list edges[][] where for each index i, there is an edge from edges[i][0] to edges[i][1] with weight edges[i][2]. Example: In
11 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 < i and A[j] > 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
Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method
Given a connected acyclic graph, a source vertex and a destination vertex, your task is to count the number of vertices between the given source and destination vertex by Disjoint Union Method . Examples: Input : 1 4 4 5 4 2 2 6 6 3 1 3 Output : 3 In the input 6 is the total number of vertices labeled from 1 to 6 and the next 5 lines are the connec
10 min read
DFS for a n-ary tree (acyclic graph) represented as adjacency list
A tree consisting of n nodes is given, we need to print its DFS. Examples : Input : Edges of graph 1 2 1 3 2 4 3 5 Output : 1 2 4 3 5 A simple solution is to do implement standard DFS. We can modify our approach to avoid extra space for visited nodes. Instead of using the visited array, we can keep track of parent. We traverse all adjacent nodes bu
4 min read
CSES Solutions - Acyclic Graph Edges
Given an undirected graph, the task is to choose a direction for each edge so that the resulting directed graph is acyclic. You can print any valid solution. Example:Input: n = 3, m = 3, edge = {{1, 2}, {2, 3}, {3, 1}}Output: 1 22 31 3Explanation: Connecting the graph in this manner will result in directed acyclic graph. Input: n = 4, m = 4, edge =
2 min read
Comparison among Greedy, Divide and Conquer and Dynamic Programming algorithm
Greedy algorithm, divide and conquer algorithm, and dynamic programming algorithm are three common algorithmic paradigms used to solve problems. Here's a comparison among these algorithms: Approach:Greedy algorithm: Makes locally optimal choices at each step with the hope of finding a global optimum.Divide and conquer algorithm: Breaks down a probl
4 min read
three90RightbarBannerImg