# Possible walks from a source to a destination with exactly k edges

Misc AlgorithmsAlgorithmsData Structure

A directed graph is given. Another two vertices u and v are also given, u is the starting vertex, and v is the ending vertex. Our task is to find a number of walks from vertex u to v with exactly k edges. The value of k is also provided in the algorithm.

By using dynamic programming, we need to create a 3D table, Where the row will point the values of u, columns will point the values v and depth will be used to track the number of edges from start to end.

## Input and Output

Input:
The adjacency matrix of the graph: The destination vertex is 3. K = 2
0 1 1 1
0 0 0 1
0 0 0 1
0 0 0 0
Output:
There are 2 Possible Walks, from 0 to 3 with 2 edges.

## Algorithm

numberOdWalks(u, v, k)

Input: The start vertex u, the end vertex v, the number of edges k.

Output: Number of possible walks with k edges.

Begin
define 3D array count of order (n x n x k+1)    //n is number of vertices
for edge in range 0 to k, do
for i in range 0 to n-1, do
for j in range 0 to n-1, do
count[i, j, edge] := 0
if edge = 0 and i = j, then
count[i, j, edge] := 1
if edge = 1 and (i, j) is connected, then
count[i, j, edge] := 1
if edge > 1, then
for a in range 0 to n, and adjacent with i do
count[i, j, edge] := count[i, j, edge] + count[a, j, edge - 1]
done
done
done
done
return count[u, v, k]
End

## Example

#include <iostream>
#define NODE 7
using namespace std;

int graph[NODE][NODE] = {
{0, 1, 1, 1},
{0, 0, 0, 1},
{0, 0, 0, 1},
{0, 0, 0, 0}
};

int numberOfWalks(int u, int v, int k) {
int count[NODE][NODE][k+1];

for (int edge = 0; edge <= k; edge++) {           //for k edges (0..k)
for (int i = 0; i < NODE; i++) {
for (int j = 0; j < NODE; j++) {
count[i][j][edge] = 0;               //initially all values are 0

if (edge == 0 && i == j)            //when e is 0 and ith and jth node are same, only one path
count[i][j][edge] = 1;
if (edge == 1 && graph[i][j])           //when e is 0 and direct path from (i to j), one path
count[i][j][edge] = 1;
if (edge >1) {                           //for more than one edges
for (int a = 0; a < NODE; a++)         // adjacent of source i
if (graph[i][a])
count[i][j][edge] += count[a][j][edge-1];
}
}
}
}
return count[u][v][k];
}

int main() {
int u = 0, v = 3, k = 2;
cout << "There are "<< numberOfWalks(u, v, k)<<" Possible Walks, from ";
cout <<u<<" to "<<v<<" with "<<k<<" edges.";
}

## Output

There are 2 Possible Walks, from 0 to 3 with 2 edges.

Published on 12-Jul-2018 08:40:13