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



In this tutorial, we will be discussing a program to find the number of walks from a source to a destination with exactly k edges.

For this we will be provided with a graph and the values of source and destination. Our task is to find all the possible paths starting from the source to the destination having exactly k edges.

Example

 Live Demo

#include <iostream> using namespace std; #define V 4 //counting walks using recursion int countwalks(int graph[][V], int u, int v, int k){    if (k == 0 && u == v)       return 1;    if (k == 1 && graph[u][v])       return 1;    if (k <= 0)       return 0;    int count = 0;       //moving to the adjacent nodes       for (int i = 0; i < V; i++)       if (graph[u][i] == 1)       count += countwalks(graph, i, v, k-1);    return count; } int main(){ int graph[V][V] = {       {0, 1, 1, 1},       {0, 0, 0, 1},       {0, 0, 0, 1},       {0, 0, 0, 0}    };    int u = 0, v = 3, k = 2;    cout << countwalks(graph, u, v, k);    return 0; }

Output

2
Updated on: 2020-02-17T10:45:04+05:30

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements