![]() |
VOOZH | about |
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 = 2Output: 2
Explanation: There are two walks from src (0) to dest (3) with exactly 2 edges: (0 β 1 β 3) and (0 β 2 β 3).
Table of Content
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.
2
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:
2