Movatterモバイル変換


[0]ホーム

URL:


Open In App
Try it on GfG Practice
redirect icon

Given adirectedgraph and two vertices src and dest, the task is to count all possible walks from vertexsrcto vertexdest that consist of exactlykedges.
The graph is represented using an adjacency matrixadj[][], whereadj[i][j] = 1 indicates the presence of a directed edge from vertexito vertexj, andadj[i][j] = 0 indicates no edge fromi toj.

Example:

Input:adj[][] = [[0, 1, 1, 1],
[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 0]]
src = 0, dest = 3, k = 2

graph

Output: 2
Explanation:There are two walks from src (0) to dest (3) with exactly 2 edges: (0 → 1 → 3) and (0 → 2 → 3).

[Brute-Force Approach] Using Recursion - O(v^k) Time and O(k) Space

The idea is torecursively explore all possible walks fromsrc todest using exactlyk edges. The thought process is that from thecurrent node, we try all itsadjacent neighbors and reducek by 1 in each recursive call. Ifk becomes 0, we check whether we’ve reached thedestination — if yes, that’s a valid walk.

C++
// C++ Code to count walks from src to dest// with exactly k edges using recursion#include<iostream>#include<vector>usingnamespacestd;// Function to count all walks from src to dest// using exactly k edgesintcountWalks(vector<vector<int>>&adj,intsrc,intdest,intk){// Base Case: If k is 0 and src is same as destif(k==0&&src==dest){return1;}// If k is 0 and src is not dest, no walk possibleif(k==0){return0;}intcount=0;// Try all adjacent vertices from srcfor(inti=0;i<adj.size();i++){// If there is an edge from src to iif(adj[src][i]==1){// Recur for the remaining k-1 edgescount+=countWalks(adj,i,dest,k-1);}}returncount;}intmain(){vector<vector<int>>adj={{0,1,1,1},{0,0,0,1},{0,0,0,1},{0,0,0,0}};intsrc=0,dest=3,k=2;cout<<countWalks(adj,src,dest,k);return0;}
Java
// Java Code to count walks from src to dest// with exactly k edges using recursionclassGfG{// Function to count all walks from src to dest// using exactly k edgesstaticintcountWalks(int[][]adj,intsrc,intdest,intk){// Base Case: If k is 0 and src is same as destif(k==0&&src==dest){return1;}// If k is 0 and src is not dest, no walk possibleif(k==0){return0;}intcount=0;// Try all adjacent vertices from srcfor(inti=0;i<adj.length;i++){// If there is an edge from src to iif(adj[src][i]==1){// Recur for the remaining k-1 edgescount+=countWalks(adj,i,dest,k-1);}}returncount;}publicstaticvoidmain(String[]args){int[][]adj={{0,1,1,1},{0,0,0,1},{0,0,0,1},{0,0,0,0}};intsrc=0,dest=3,k=2;System.out.println(countWalks(adj,src,dest,k));}}
Python
# Python Code to count walks from src to dest# with exactly k edges using recursion# Function to count all walks from src to dest# using exactly k edgesdefcountWalks(adj,src,dest,k):# Base Case: If k is 0 and src is same as destifk==0andsrc==dest:return1# If k is 0 and src is not dest, no walk possibleifk==0:return0count=0# Try all adjacent vertices from srcforiinrange(len(adj)):# If there is an edge from src to iifadj[src][i]==1:# Recur for the remaining k-1 edgescount+=countWalks(adj,i,dest,k-1)returncountif__name__=="__main__":adj=[[0,1,1,1],[0,0,0,1],[0,0,0,1],[0,0,0,0]]src=0dest=3k=2print(countWalks(adj,src,dest,k))
C#
// C# Code to count walks from src to dest// with exactly k edges using recursionusingSystem;classGfG{// Function to count all walks from src to dest// using exactly k edgesstaticintcountWalks(int[,]adj,intsrc,intdest,intk){// Base Case: If k is 0 and src is same as destif(k==0&&src==dest){return1;}// If k is 0 and src is not dest, no walk possibleif(k==0){return0;}intcount=0;// Try all adjacent vertices from srcfor(inti=0;i<adj.GetLength(0);i++){// If there is an edge from src to iif(adj[src,i]==1){// Recur for the remaining k-1 edgescount+=countWalks(adj,i,dest,k-1);}}returncount;}staticvoidMain(){int[,]adj={{0,1,1,1},{0,0,0,1},{0,0,0,1},{0,0,0,0}};intsrc=0,dest=3,k=2;Console.WriteLine(countWalks(adj,src,dest,k));}}
JavaScript
// JavaScript Code to count walks from src to dest// with exactly k edges using recursion// Function to count all walks from src to dest// using exactly k edgesfunctioncountWalks(adj,src,dest,k){// Base Case: If k is 0 and src is same as destif(k===0&&src===dest){return1;}// If k is 0 and src is not dest, no walk possibleif(k===0){return0;}letcount=0;// Try all adjacent vertices from srcfor(leti=0;i<adj.length;i++){// If there is an edge from src to iif(adj[src][i]===1){// Recur for the remaining k-1 edgescount+=countWalks(adj,i,dest,k-1);}}returncount;}// Driver Codeletadj=[[0,1,1,1],[0,0,0,1],[0,0,0,1],[0,0,0,0]];letsrc=0,dest=3,k=2;console.log(countWalks(adj,src,dest,k));

Output
2

[Expected Approach] Using Dynamic Programming - O(k*(v^3)) Time and O(k*(v^2)) Space

The idea is tocount walks by building the solutionbottom-up usingdynamic programming. The thought process is that if you know how many ways you can go fromone node to another in k-1 edges, you can use that to compute walks ofk edges by adding one more valid step.
We define a3D DP table dp[e][i][j] where each entry stores the number of walks from node i to node j usingexactly e edges.
The observation is that a walk of length k from i to j can be formed by going from i to any neighbor a, and then completing the remainingk-1 steps from a to j.

Steps to implement the above idea:

  • Create a3D DP table dp where dp[e][i][j] stores walks fromi to j usinge edges.
  • Initializedp[0][i][i] = 1 for all nodes i since 0-length walk from a node to itself is 1.
  • Iterateefrom 1 to k to build solutions incrementally for each edge count up tok.
  • For each edge count e, iterate over all pairs(i, j) representing source and destination nodes.
  • For each(i, j) pair, loop over all intermediate nodesa that are direct neighbors of i.
  • If there's an edge fromi to a, adddp[e-1][a][j] todp[e][i][j] to extend the walk.
  • Finally, returndp[k][src][dest] which stores walks from src to dest using exactlyk edges.
C++
// C++ Code to count walks from src to dest// with exactly k edges using DP#include<iostream>#include<vector>usingnamespacestd;// Function to count all walks from src to dest// using exactly k edges with bottom-up DPintcountWalks(vector<vector<int>>&adj,intsrc,intdest,intk){intv=adj.size();// dp[e][i][j]: number of walks from i to j using e edgesvector<vector<vector<int>>>dp(k+1,vector<vector<int>>(v,vector<int>(v,0)));// Base case: walks from i to j with 0 edgesfor(inti=0;i<v;i++){dp[0][i][i]=1;}// Build the table for all edge counts from 1 to kfor(inte=1;e<=k;e++){for(inti=0;i<v;i++){for(intj=0;j<v;j++){// Consider all intermediate verticesfor(inta=0;a<v;a++){// If there's an edge from i to aif(adj[i][a]==1){dp[e][i][j]+=dp[e-1][a][j];}}}}}returndp[k][src][dest];}intmain(){vector<vector<int>>adj={{0,1,1,1},{0,0,0,1},{0,0,0,1},{0,0,0,0}};intsrc=0,dest=3,k=2;cout<<countWalks(adj,src,dest,k);return0;}
Java
// Java Code to count walks from src to dest// with exactly k edges using DPclassGfG{// Function to count all walks from src to dest// using exactly k edges with bottom-up DPstaticintcountWalks(int[][]adj,intsrc,intdest,intk){intv=adj.length;// dp[e][i][j]: number of walks from i to j using e edgesint[][][]dp=newint[k+1][v][v];// Base case: walks from i to j with 0 edgesfor(inti=0;i<v;i++){dp[0][i][i]=1;}// Build the table for all edge counts from 1 to kfor(inte=1;e<=k;e++){for(inti=0;i<v;i++){for(intj=0;j<v;j++){// Consider all intermediate verticesfor(inta=0;a<v;a++){// If there's an edge from i to aif(adj[i][a]==1){dp[e][i][j]+=dp[e-1][a][j];}}}}}returndp[k][src][dest];}publicstaticvoidmain(String[]args){int[][]adj={{0,1,1,1},{0,0,0,1},{0,0,0,1},{0,0,0,0}};intsrc=0,dest=3,k=2;System.out.println(countWalks(adj,src,dest,k));}}
Python
# Python Code to count walks from src to dest# with exactly k edges using DP# Function to count all walks from src to dest# using exactly k edges with bottom-up DPdefcountWalks(adj,src,dest,k):v=len(adj)# dp[e][i][j]: number of walks from i to j using e edgesdp=[[[0for_inrange(v)]for_inrange(v)]for_inrange(k+1)]# Base case: walks from i to j with 0 edgesforiinrange(v):dp[0][i][i]=1# Build the table for all edge counts from 1 to kforeinrange(1,k+1):foriinrange(v):forjinrange(v):# Consider all intermediate verticesforainrange(v):# If there's an edge from i to aifadj[i][a]==1:dp[e][i][j]+=dp[e-1][a][j]returndp[k][src][dest]if__name__=="__main__":adj=[[0,1,1,1],[0,0,0,1],[0,0,0,1],[0,0,0,0]]src,dest,k=0,3,2print(countWalks(adj,src,dest,k))
C#
// C# Code to count walks from src to dest// with exactly k edges using DPusingSystem;classGfG{// Function to count all walks from src to dest// using exactly k edges with bottom-up DPpublicstaticintcountWalks(int[][]adj,intsrc,intdest,intk){intv=adj.Length;// dp[e][i][j]: number of walks from i to j using e edgesint[,,]dp=newint[k+1,v,v];// Base case: walks from i to j with 0 edgesfor(inti=0;i<v;i++){dp[0,i,i]=1;}// Build the table for all edge counts from 1 to kfor(inte=1;e<=k;e++){for(inti=0;i<v;i++){for(intj=0;j<v;j++){// Consider all intermediate verticesfor(inta=0;a<v;a++){// If there's an edge from i to aif(adj[i][a]==1){dp[e,i,j]+=dp[e-1,a,j];}}}}}returndp[k,src,dest];}staticvoidMain(){int[][]adj=newint[][]{newint[]{0,1,1,1},newint[]{0,0,0,1},newint[]{0,0,0,1},newint[]{0,0,0,0}};intsrc=0,dest=3,k=2;Console.WriteLine(countWalks(adj,src,dest,k));}}
JavaScript
// JavaScript Code to count walks from src to dest// with exactly k edges using DP// Function to count all walks from src to dest// using exactly k edges with bottom-up DPfunctioncountWalks(adj,src,dest,k){constv=adj.length;// dp[e][i][j]: number of walks from i to j using e edgesconstdp=Array.from({length:k+1},()=>Array.from({length:v},()=>Array(v).fill(0)));// Base case: walks from i to j with 0 edgesfor(leti=0;i<v;i++){dp[0][i][i]=1;}// Build the table for all edge counts from 1 to kfor(lete=1;e<=k;e++){for(leti=0;i<v;i++){for(letj=0;j<v;j++){// Consider all intermediate verticesfor(leta=0;a<v;a++){// If there's an edge from i to aif(adj[i][a]===1){dp[e][i][j]+=dp[e-1][a][j];}}}}}returndp[k][src][dest];}// Driver Codeconstadj=[[0,1,1,1],[0,0,0,1],[0,0,0,1],[0,0,0,0]];constsrc=0,dest=3,k=2;console.log(countWalks(adj,src,dest,k));

Output
2



Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp