Possible paths | Practice | GeeksforGeeks

Given a directed graph and two vertices ‘u’ and ‘v’ in it. Find the number of possible walks from ‘u’ to ‘v’ with exactly k edges on the walk modulo 109+7.
Note : There can be a cycle in the graph and an edge can be travelled multiple times.
Example 1:
Input 1: graph = {{0,1,1,1},{0,0,0,1}, 
{0,0,0,1}, {0,0,0,0}}, u = 0, v = 3, k = 2
Output: 2
Explanation: Let source ‘u’ be vertex 0, 
destination ‘v’ be 3 and k be 2. The output 
should be 2 as there are two walk from 0 to 
3 with exactly 2 edges. The walks are {0, 2, 3}
and {0, 1, 3}.


Your Task:
You don't need to read or print anything. Your task is to complete the function MinimumWalk() which takes graph, u, v and k as input parameter and returns total possible paths from u to v using exactly k edges modulo 109+7.
Note: In graph, if graph[i][j] = 1, it means there is an directed edge from vertex i to j.
 
Expected Time Complexity: O(n3)
Expected Space Complexity: O(n3)
 
Constraints:
1 ≤ n ≤ 50
1 ≤ k ≤ n
0 ≤ u, v ≤ n-1
+1
aloksinghbais021 week ago
C++ solution having time complexity as O(N^3) and space complexity as O(N^3) is as follows :- 
 
Execution Time :- 0.03 / 1.26 sec 
 
vector<int> adj[51];   int mod = (int)1e9 + 7;   long long int dp[51][51];      long long int helper(int node,int des,int k){       if(k == 0){           return node == des ? 1LL : 0;       }              if(dp[node][k] != -1) return dp[node][k];              long long int cnt = 0;       for(auto choice: adj[node]){           cnt = (cnt + 1LL*helper(choice,des,k-1)) % mod;       }       return (dp[node][k] = cnt);   }   int MinimumWalk(vector<vector<int>>&graph, int u, int v, int k){    int n = graph.size();    for(int i = 0; i < n; i++){        for(int j = 0; j < n; j++){            if(graph[i][j] == 1){                adj[i].push_back(j);            }        }    }        memset(dp,-1,sizeof(dp));    return (int)helper(u,v,k);}
0
aditya048481 month ago
# TIME complexity = O(V*K + V*V)
# SPACE complexity = O(V*K)

from collections import defaultdict

class Solution:
    
    def helperFunc(self, g, v, curr, p, table):
        if p == 0:
            if curr == v:
                return 1
            else:
                return 0
                
        if (curr, p) not in table:
            
            table[(curr, p)] = 0
            for x in g[curr]:
                table[(curr, p)] = (table[(curr, p)] + self.helperFunc(g, v, x, p-1, table )) % 1000000007
        
        
        return table[(curr, p)] 
    
	def MinimumWalk(self, graph, u, v, k):
	
	    g = defaultdict(list)
	    
	    for i in range(len(graph)):
	        for j in range(len(graph[i])):
	            if graph[i][j] == 1:
	                g[i].append(j)
	        
	    table = {}
	    result = self.helperFunc(g, v, u, k, table) % 1000000007
	    return result 
0
belalazam31 month ago
int mod=1e9 +7;   unordered_map<int,unordered_map<int,int>>dp;   int dfs(int u,int v,vector<vector<int>>&graph,int k)   {       if(u==v and k==0)       {return 1;}       if(k==0)return 0;       if(dp[u][k]!=0)return dp[u][k];       int x=0;       for(auto i:graph[u])       {           if(i==1)dp[u][k]=(dp[u][k]+dfs(x,v,graph,k-1))%mod;           x++;       }       return dp[u][k]%mod;   }int MinimumWalk(vector<vector<int>>&graph, int u, int v, int k){    return dfs(u,v,graph,k);}
+2
sbh698405 months ago
The solution in the editorial is O(n^4) time. I personally solved this using matrix exponentiation in O(n^3 log n)
+1
rohitjug19csPremium5 months ago
JAVA O(k.n.n) Time complexity , and O(n.k) Space Complexity Solution
public int MinimumWalk(int[][] graph, int u, int v, int k)
    {
      int m = (int)(Math.pow(10, 9) + 7);
      int n = graph.length;  
      int dp[][] = new int[n][k+1];
      
      dp[u][0] = 1;
      for(int j=0; j<k; j++){
        for(int i=0; i<n; i++){
           if(dp[i][j] > 0){
             for(int l=0; l<n; l++)
                if(graph[i][l]==1)dp[l][j+1] = (dp[l][j+1]+dp[i][j])%m;
           }
        }   
      }

       return dp[v][k];
    }
+2
ritumodi55 months ago
We can solve this using dynamic programming.
 
We start at the source vertex u, and for each neighbor of vertex u, run a dfs from that neighbor with k-1 edges needed.
 
Here's a recursive memoised Java solution:
 
class Solution{
   private static final int mod = (int)1e9+7;
   
   public int MinimumWalk(int[][] graph, int u, int v, int k){
       return helper(graph, u, v, k, new Integer[graph.length][k+1]); 
   }
   
   private int helper(int[][] graph, int curr, int dest, int k, Integer[][] memo){
       if(k == 0) return curr == dest ? 1 : 0;
       if(memo[curr][k] != null) return memo[curr][k];
       
       int ans = 0;
       for(int i = 0; i < graph[0].length; i++)
           if (graph[curr][i] == 1)
               ans = (ans + helper(graph, i, dest, k-1, memo)) % mod;
       
       return memo[curr][k] = ans % mod;
   }
}
0
rajsonkar36315 months ago
12
+1
ritikraj6120
This comment was deleted.
-1
mvanshika5 months ago
The allowed time complexity is On3 my code is of On2 yet it is exceeding the time limit ... can anyone suggest what is wrong in my code
class Solution{   public int MinimumWalk(int[][] graph, int u, int v, int k)   {       // Code here       int count =0;       for(int i=0;i<graph.length;i++)       {           if(graph[u][i]==1)           {               count=(count+dfs(graph,i,v,k,1)%1000000007)%1000000007;           }       }       return count;   }   public int dfs(int[][] graph,int curr, int v, int k, int edge)   {       if(edge>k)           return 0;       if(curr==v&&edge==k)           return 1;       int count=0;       for(int i=0;i<graph.length;i++)       {           if(graph[curr][i]==1)           {               count=(count+dfs(graph,i,v,k,edge+1)%1000000007)%1000000007;           }       }              return count;   }}
0
tushargupta19995 months ago
C++ DFS + Caching
class Solution {
    int dfs(vector<vector<int>>&graph, vector<vector<long>>&dp, int cur, int target, int k) {
        if(dp[cur][k] != -1) {
            return dp[cur][k];
        }
        dp[cur][k] = 0;
        for(int i=0; i<graph.size(); i++) {
            if(graph[cur][i]) {
                dp[cur][k] = (dp[cur][k] + dfs(graph, dp, i, target, k-1))%int(1e9+7);
            }
        }
        return dp[cur][k];
    }
  public:
	int MinimumWalk(vector<vector<int>>&graph, int u, int v, int k){
	    vector<vector<long>> dp(graph.size(), vector<long>(k+1, -1));
	    dp[v][0] = 1;
	    for(int i=0; i<graph.size(); i++) {
	        if(i != v) dp[i][0] = 0;
	    }
	    dfs(graph, dp, u, v, k);
	    return dp[u][k];
	}
};
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.