Possible paths between 2 vertices | Practice | GeeksforGeeks

Given a Directed Graph having V nodes numbered from 1 to V, and E directed edges. Given two nodes, source and destination, count the number of ways or paths between these two vertices in the directed graph. These paths should not contain any cycle.
Note: Graph doesn't contain multiple edges, self-loop, and cycles.

Example 1:
Input:

Output: 4
Explanation: 
There are 4 paths from 0 to 4.
0 -> 4
0 -> 1 -> 4
0 -> 2 -> 4
0 -> 1 -> 3 -> 2 -> 4


Example 2:
Input:

Output: 3
Explanation:
There are 3 paths from 0 to 3.
0 -> 3
0 -> 1 -> 3
0 -> 1 -> 2 -> 3


Your task:
You don't need to read, input, or print anything. Your task is to complete the function countPaths(), which takes the integer V denoting the number of vertices, adjacency list adj, integer source, and destination as input parameters and returns the number of paths in the graph from the source vertex to the destination vertex.

Expected Time Complexity: O(V!)
Expected Auxiliary Space: O(V)

Constraints:
1 ≤ V, E ≤ 100
1 ≤ source, destination ≤ V
+1
kharsh8224 days ago
Java Easy Solution
// { Driver Code Starts
// Initial Template for Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
    public static void main(String[] args) throws IOException {
        BufferedReader br =
            new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine().trim());
        while (T-- > 0) {
            String[] s = br.readLine().trim().split(" ");
            int V = Integer.parseInt(s[0]);
            int E = Integer.parseInt(s[1]);
            ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
            for (int i = 0; i < V; i++) adj.add(i, new ArrayList<Integer>());
            for (int i = 0; i < E; i++) {
                String[] S = br.readLine().trim().split(" ");
                int u = Integer.parseInt(S[0]);
                int v = Integer.parseInt(S[1]);
                adj.get(u).add(v);
                // adj.get(v).add(u);
            }
            String[] S1 = br.readLine().trim().split(" ");
            int source = Integer.parseInt(S1[0]);
            int destination = Integer.parseInt(S1[1]);
            Solution obj = new Solution();
            System.out.println(obj.countPaths(V, adj, source, destination));
        }
    }
}
// } Driver Code Ends


class Solution {
    // Function to count paths between two vertices in a directed graph.
    int count;
    public int countPaths(int V, ArrayList<ArrayList<Integer>> adj, int source,
                   int destination) {
        // Code here
       
        boolean [] visited=new boolean[V];
        helper(adj,source,destination,visited,count);
        return count;
    }
    
    public int helper(ArrayList<ArrayList<Integer>> adj,int src, int desc,boolean [] visited,int n){
        if(src==desc){
            
            count++;
            return 1;
        }
        visited[src]=true;
        
        for(int a :adj.get(src)){
            if(visited[a]==false){
                helper(adj,a,desc,visited,count);
            }
        }
        
        visited[src]=false;
        return count;
    }
}
0
robinsdeepak2 weeks ago
Python DFS 0.06 Second
 
class Solution:
    def countPaths(self, V, adj, source, dest):
        count = 0
        
        def dfs(i):
            if i == dest:
                nonlocal count
                count += 1
                return
            for j in adj[i]:
                dfs(j)
        
        dfs(source)
        
        return count
0
phenomenal13 weeks ago
JAVA Solution(DFS Approach):
class Solution {
    
    int count = 0;
    public int countPaths(int V, ArrayList<ArrayList<Integer>> adj, int source,
                   int destination) {
        
        boolean vis[] = new boolean[V+1];
        vis[source]=true;
        dfs(source,destination,vis,adj);
        return count;
    }
    
    void dfs(int src,int dest,boolean vis[],ArrayList<ArrayList<Integer>> adj)
    {
        if(src == dest)
        {
            count++;
            return;
        }
        
        for(int x:adj.get(src))
        {
            if(!vis[x])
            {
                vis[x]=true;
                dfs(x,dest,vis,adj);
                vis[x]=false;
            }
        }
    }
}
0
alamfarhan3891 month ago
int solve(vector<int> adj[], int src, int dest, int par) {       if(src == dest) return 1;       int ans = 0;       for(int v : adj[src]) {           if(v != par) {               ans += solve(adj, v, dest, src);           }       }       return ans;   }   int countPaths(int V, vector<int> adj[], int source, int destination) {       return solve(adj, source, destination, -1);   }
0
tthakare732 months ago
JAVA Solution
class Solution {
    
    public static int DFS(int src, int destination, int pathCount, ArrayList<ArrayList<Integer>> adj){
       if(src == destination) {
           pathCount++;
       } else {
           for(Integer item : adj.get(src)){
               pathCount = DFS(item, destination, pathCount, adj);
           }
       }
       return pathCount;
    }
    // Function to count paths between two vertices in a directed graph.
    public int countPaths(int V, ArrayList<ArrayList<Integer>> adj, int src, int destination) {
        // Code here
        int count = 0;
        count = DFS(src, destination, count, adj);
        return count;
    }
}
+1
ayushnautiyal11102 months ago
int countPaths(int V, vector<int> adj[], int source, int destination) {       int count=0;       queue<int>q;       q.push(source);       if(source==destination){           return 1;       }       while(!q.empty())       {           int curr=q.front();           q.pop();           for(auto x:adj[curr]){               if(x==destination){                   count++;               }                   q.push(x);                          }       }       return count;   }
0
rupalbemarkar20022 months ago
int ans=0;   int countPaths(int V, vector<int> adj[], int source, int destination)    {       // Code here       if(source==destination)       {           ans++;           return ans;       }       for(int i=0;i<adj[source].size();i++)       {         countPaths(V,adj,adj[source][i],destination);       }       return ans;   }
0
jk30012 months ago
This question test cases needs to improve we are not considering going through a node again again. What if we are going though a articulation point. We could save lots of time by using DP here.
Optimized Code:
int dfs(int u, vector<int> adj[], int src, int des, vector<int> &dp){
    if(u == des)    return dp[u] = 1;
    int cnt = 0;
    for(auto x:adj[u]){
        if(dp[x] == -1){
            dp[x] = dfs(x, adj, src, des, dp);
        }
        cnt += dp[x];
    }
    return cnt;
}
    
class Solution{
  public:
    // Function to count paths between two vertices in a directed graph.
    int countPaths(int V, vector<int> adj[], int source, int destination) {
        vector<int> dp(V+1, -1);
        return dfs(source, adj, source, destination, dp);
    }
};
0
arankeparth19122 months ago
More optimized approach:
int dp[1000000];   int num_paths(int u,vector<int>adj[],int dest, map<int,int>&visited) {       if(u==dest)           return 1;       visited[u]=1;       int ans=0;       for(auto i=adj[u].begin();i!=adj[u].end();i++) {           if(!visited[*i]) {             ans+=num_paths(*i,adj,dest,visited);             }           else if(dp[*i]!=-1) {               ans+=dp[*i];           }       }       return dp[u]=ans;   }   int countPaths(int V, vector<int> adj[], int source, int destination) {       map<int,int>visited;              return num_paths(source,adj,destination,visited);   }
 
please tell me if this will give us o(n^2) time complexity!!
0
mohankumarit20012 months ago
BFS || 0 ms || C++
int countPaths(int V, vector<int> adj[], int source, int destination) {
        // Code here
        int res = 0;
        queue<int> q;
        q.push(source);
        while(!q.empty()){
            int parent = q.front();q.pop();
            if(parent==destination){
                res++;
                continue;
            }
            for(int i:adj[parent]){
                if(i==source)continue;
                q.push(i);
            }
        }
        return res;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.