Skip to content
Related Articles

Related Articles

Number of paths from source to destination in a directed acyclic graph

Improve Article
Save Article
Like Article
  • Difficulty Level : Hard
  • Last Updated : 19 Feb, 2022

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:
Explanation: 
0 -> 2 -> 3 -> 4 
0 -> 3 -> 4 
0 -> 4 

Input: source = 0, destination = 1 
Output:
Explanation: There exists only one path 0->1  

Approach: Let f(u) be the number of ways one can travel from node u to destination vertex. Hence, f(source) is required answer. As f(destination) = 1 here so there is just one path from destination to itself. One can observe, f(u) depends on nothing other than the f values of all the nodes which are possible to travel from u. It makes sense because the number of different paths from u to the destination is the sum of all different paths from v1, v2, v3… v-n to destination vertex where v1 to v-n are all the vertices that have a direct path from vertex u. This approach, however, is too slow to be useful. Each function call branches out into further calls, and that branches into further calls, until each and every path is explored once. 

The problem with this approach is the calculation of f(u) again and again each time the function is called with argument u. Since this problem exhibits both overlapping subproblems and optimal substructure, dynamic programming is applicable here. In order to evaluate f(u) for each u just once, evaluate f(v) for all v that can be visited from u before evaluating f(u). This condition is satisfied by reverse topological sorted order of the nodes of the graph. 

Below is the implementation of the above approach:  

C++




// C++ program for Number of paths
// from one vertex to another vertex
//  in a Directed Acyclic Graph
#include <bits/stdc++.h>
using namespace std;
#define MAXN 1000005
 
// to make graph
vector<int> v[MAXN];
 
// function to add edge in graph
void add_edge(int a, int b, int fre[])
{
    // there is path from a to b.
    v[a].push_back(b);
    fre[b]++;
}
 
// function to make topological sorting
vector<int> topological_sorting(int fre[], int n)
{
    queue<int> q;
 
    // insert all vertices which
    // don't have any parent.
    for (int i = 0; i < n; i++)
        if (!fre[i])
            q.push(i);
 
    vector<int> l;
 
    // using kahn's algorithm
    // for topological sorting
    while (!q.empty()) {
        int u = q.front();
        q.pop();
 
        // insert front element of queue to vector
        l.push_back(u);
 
        // go through all it's childs
        for (int i = 0; i < v[u].size(); i++) {
            fre[v[u][i]]--;
 
            // whenever the frequency is zero then add
            // this vertex to queue.
            if (!fre[v[u][i]])
                q.push(v[u][i]);
        }
    }
    return l;
}
 
// Function that returns the number of paths
int numberofPaths(int source, int destination, int n, int fre[])
{
 
// make topological sorting
    vector<int> s = topological_sorting(fre, n);
 
    // to store required answer.
    int dp[n] = { 0 };
 
    // answer from destination
    // to destination is 1.
    dp[destination] = 1;
 
    // traverse in reverse order
    for (int i = s.size() - 1; i >= 0; i--) {
        for (int j = 0; j < v[s[i]].size(); j++) {
            dp[s[i]] += dp[v[s[i]][j]];
        }
    }
 
    return dp;
}
 
// Driver code
int main()
{
 
    // here vertices are numbered from 0 to n-1.
    int n = 5;
    int source = 0, destination = 4;
 
    // to count number of vertex which don't
    // have any parents.
    int fre[n] = { 0 };
 
    // to add all edges of graph
    add_edge(0, 1, fre);
    add_edge(0, 2, fre);
    add_edge(0, 3, fre);
    add_edge(0, 4, fre);
    add_edge(2, 3, fre);
    add_edge(3, 4, fre);
 
    // Function that returns the number of paths
    cout << numberofPaths(source, destination, n, fre);
}

Python3




# Python3 program for Number of paths
# from one vertex to another vertex
# in a Directed Acyclic Graph
from collections import deque
MAXN = 1000005
 
# to make graph
v = [[] for i in range(MAXN)]
 
# function to add edge in graph
def add_edge(a, b, fre):
   
    # there is path from a to b.
    v[a].append(b)
    fre[b] += 1
 
# function to make topological sorting
def topological_sorting(fre, n):
    q = deque()
 
    # insert all vertices which
    # don't have any parent.
    for i in range(n):
        if (not fre[i]):
            q.append(i)
 
    l = []
 
    # using kahn's algorithm
    # for topological sorting
    while (len(q) > 0):
        u = q.popleft()
        #q.pop()
 
        # insert front element of queue to vector
        l.append(u)
 
        # go through all it's childs
        for i in range(len(v[u])):
            fre[v[u][i]] -= 1
 
            # whenever the frequency is zero then add
            # this vertex to queue.
            if (not fre[v[u][i]]):
                q.append(v[u][i])
    return l
 
# Function that returns the number of paths
def numberofPaths(source, destination, n, fre):
 
# make topological sorting
    s = topological_sorting(fre, n)
 
    # to store required answer.
    dp = [0]*n
 
    # answer from destination
    # to destination is 1.
    dp[destination] = 1
 
    # traverse in reverse order
    for i in range(len(s) - 1,-1,-1):
        for j in range(len(v[s[i]])):
            dp[s[i]] += dp[v[s[i]][j]]
    return dp
 
# Driver code
if __name__ == '__main__':
 
    # here vertices are numbered from 0 to n-1.
    n = 5
    source, destination = 0, 4
 
    # to count number of vertex which don't
    # have any parents.
    fre = [0]*n
 
    # to add all edges of graph
    add_edge(0, 1, fre)
    add_edge(0, 2, fre)
    add_edge(0, 3, fre)
    add_edge(0, 4, fre)
    add_edge(2, 3, fre)
    add_edge(3, 4, fre)
 
    # Function that returns the number of paths
    print (numberofPaths(source, destination, n, fre))
 
# This code is contributed by mohit kumar 29.

Java




// Java program for Number of paths
// from one vertex to another vertex
//  in a Directed Acyclic Graph
 
import java.util.*;
 
class GFG{
static final int MAXN = 1000005;
 
// to make graph
static Vector<Integer> []v = new Vector[MAXN];
static {
    for (int i = 0; i < v.length; i++)
        v[i] = new Vector<Integer>();
}
// function to add edge in graph
static void add_edge(int a, int b, int fre[])
{
    // there is path from a to b.
    v[a].add(b);
    fre[b]++;
}
 
// function to make topological sorting
static Vector<Integer> topological_sorting(int fre[], int n)
{
    Queue<Integer> q = new LinkedList<Integer>();
 
    // insert all vertices which
    // don't have any parent.
    for (int i = 0; i < n; i++)
        if (fre[i]==0)
            q.add(i);
 
    Vector<Integer> l = new Vector<Integer>();
 
    // using kahn's algorithm
    // for topological sorting
    while (!q.isEmpty()) {
        int u = q.peek();
        q.remove();
 
        // insert front element of queue to vector
        l.add(u);
 
        // go through all it's childs
        for (int i = 0; i < v[u].size(); i++) {
            fre[v[u].get(i)]--;
 
            // whenever the frequency is zero then add
            // this vertex to queue.
            if (fre[v[u].get(i)]==0)
                q.add(v[u].get(i));
        }
    }
    return l;
}
 
// Function that returns the number of paths
static int numberofPaths(int source, int destination, int n, int fre[])
{
 
// make topological sorting
    Vector<Integer> s = topological_sorting(fre, n);
 
    // to store required answer.
    int dp[] = new int[n];
 
    // answer from destination
    // to destination is 1.
    dp[destination] = 1;
 
    // traverse in reverse order
    for (int i = s.size() - 1; i >= 0; i--) {
        for (int j = 0; j < v[s.get(i)].size(); j++) {
            dp[s.get(i)] += dp[v[s.get(i)].get(j)];
        }
    }
 
    return dp;
}
 
// Driver code
public static void main(String[] args)
{
 
    // here vertices are numbered from 0 to n-1.
    int n = 5;
    int source = 0, destination = 4;
 
    // to count number of vertex which don't
    // have any parents.
    int fre[] = new int[n];
 
    // to add all edges of graph
    add_edge(0, 1, fre);
    add_edge(0, 2, fre);
    add_edge(0, 3, fre);
    add_edge(0, 4, fre);
    add_edge(2, 3, fre);
    add_edge(3, 4, fre);
 
    // Function that returns the number of paths
    System.out.print(numberofPaths(source, destination, n, fre));
}
}
// This code contributed by shikhasingrajput
Output
3

Method 2 : ( Top down dp)

Let us consider the graph below

Let us consider source as 0 ( zero ) and destination as 4 . Now we need to find the number of ways to reach 4 from the source i.e., 0 . One of the basic intuition is that if we are already at the destination we have found 1 valid path . Let us consider that our source and destination are different as of now we don’t know in how many ways we can reach from source to destination . But if there exists some neighbours for source then if the neighbours can reach the destination via some path then in all of these paths we can just append source to get the number of ways to reach the destination from source .

If we can visualise it : 

In order to compute the number of ways to reach from source to destination i.e., source  to destination  . If the neighbours of source i.e., 0 can reach the destination ( 4 ) via some path , then we can just append the source to get the number of ways that the source can reach the destination .

source ( 0 ) neighbours are 4 , 3 , 2

4 is the destination so we have found 1 valid path . So in order to get the path from source we can just append the source in front of destination i.e., 0 -> 4 .

The number of ways 3 can reach the 4 is 3 -> 4 is the only possible way . In this case we can just append source to get the number of ways to reach the destination from source via 3 i.e., 0 -> 3 -> 4 . This is one more possible path .

The number of ways 2 can reach the 4 is 2 -> 3 -> 4 is the only possible way . Now we can just append the source to get the path from source to destination i.e., 0 -> 2 -> 3 -> 4 .

We have found 3 possible ways to reach the destination from source . But we can see there are some overlapping of sub – problems i.e., when we are computing the answer for 2 we are exploring the path of 3 which we have already computed . In order to avoid this we can just store the result of every vertex ones we have computed the answer to it , So that it will help us to avoid computing the solution of similar sub – problems again and again . There comes the intuition of dynamic programming .

Approach : 

  • If we are already at the destination we have found one valid path .
  • If we have not reached the destination , then the number of ways to reach the destination from the current vertex depends on the number of ways the neighbours can reach the destination . We sum all the ways and store it in the dp array .
  • If we have already computed the result of any vertex we return the answer directly . In order to identify that we have not computed the answer for any vertex we initialise the dp array with -1 ( indicates we have not computed the answer for that vertex ) .
  • If the neighbours of any vertex are unable to reach the destination we return -1 to indicate that there is no path .
  • If the number of ways are really very large we can module it with 10^9 + 7 and store the result .

Below is the C++ implementation

C++




#include <bits/stdc++.h>
using namespace std;
 
long dp[10006];
long mod = 1e9 + 7;
 
/* function which returns the number
of ways to reach from source to destination */
long countPaths(vector<vector<long> >& arr, long s, long d)
{
    /*
            if we are already at the
            destination we have found 1 valid
            path
    */
    if (s == d)
        return 1;
    /*
            if we have already computed the
            number of ways to reach the destination
            via this vertex return the answer
    */
    if (dp[s] != -1)
        return dp[s];
 
    long c = 0;
    for (long& neigh : arr[s]) {
        /*
                since the number of ways to reach the
           destination from the current vertex depends on
           the number of ways the neighbours can reach the
           destination so get all the possible ways that the
           neighbours can reach the destination
        */
        long x = countPaths(arr, neigh, d);
 
        // if we reached the destination than add it to the
        // result
        if (x != -1) {
            c = (c % mod + x % mod) % mod;
        }
    }
    /*
            if c is equal to zero that means there are no
       paths from the current vertex to the destination so
       return -1 to indicate there is no path or else store
       the c and return it
    */
    return (dp[s] = (c == 0) ? -1 : c);
}
long Possible_Paths(vector<vector<long> >& arr, long n,
                    long s, long d)
{
    // initialise the dp array with -1
    // to indicate we haven't computed
    // the answer for any vertex
    memset(dp, -1, sizeof dp);
 
    long c = countPaths(arr, s, d);
 
    // if there are no paths return 0
    if (c == -1)
        return 0;
 
    // else return c
    return c;
}
int main()
{
    long n, m, s, d;
    n = 5, m = 6, s = 0, d = 4;
    vector<vector<long> > arr(n + 1);
 
    arr[0].push_back(1);
    arr[0].push_back(2);
    arr[0].push_back(3);
    arr[0].push_back(4);
    arr[2].push_back(3);
    arr[3].push_back(4);
 
    cout << Possible_Paths(arr, n, s, d) << endl;
    return 0;
}
Output
3

Time complexity :  O ( V + E ) where V are the vertices and E are the edges .

Space complexity : O ( V + E + V ) where O ( V + E ) for adjacency list and O ( V ) for dp array .


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!