VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-possible-paths-source-destination-exactly-k-edges/

⇱ Count all possible walks from a source to a destination with exactly k edges - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count all possible walks from a source to a destination with exactly k edges

Last Updated : 12 Jun, 2025

Given a directed graph and two vertices src and dest, the task is to count all possible walks from vertex src to vertex dest that consist of exactly k edges.
The graph is represented using an adjacency matrix adj[][], where adj[i][j] = 1 indicates the presence of a directed edge from vertex i to vertex j, and adj[i][j] = 0 indicates no edge from i to j.

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 to recursively explore all possible walks from src to dest using exactly k edges. The thought process is that from the current node, we try all its adjacent neighbors and reduce k by 1 in each recursive call. If k becomes 0, we check whether we’ve reached the destination β€” if yes, that’s a valid walk.


Output
2

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

The idea is to count walks by building the solution bottom-up using dynamic programming. The thought process is that if you know how many ways you can go from one node to another in k-1 edges, you can use that to compute walks of k edges by adding one more valid step.
We define a 3D DP table dp[e][i][j] where each entry stores the number of walks from node i to node j using exactly 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 remaining k-1 steps from a to j.

Steps to implement the above idea:

  • Create a 3D DP table dp where dp[e][i][j] stores walks from i to j using e edges.
  • Initialize dp[0][i][i] = 1 for all nodes i since 0-length walk from a node to itself is 1.
  • Iterate e from 1 to k to build solutions incrementally for each edge count up to k.
  • 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 nodes a that are direct neighbors of i.
  • If there's an edge from i to a, add dp[e-1][a][j] to dp[e][i][j] to extend the walk.
  • Finally, return dp[k][src][dest] which stores walks from src to dest using exactly k edges.

Output
2


Comment