Open In App

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

Last Updated : 24 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a directed graph and two vertices ‘u’ and ‘v’ in it, count all possible walks from ‘u’ to ‘v’ with exactly k edges on the walk. 

The graph is given adjacency matrix representation where the value of graph[i][j] as 1 indicates that there is an edge from vertex i to vertex j and a value 0 indicates no edge from i to j.

For example, consider the following graph. Let source ‘u’ be vertex 0, destination ‘v’ be 3 and k be 2. The output should be 2 as there are two walks from 0 to 3 with exactly 2 edges. The walks are {0, 2, 3} and {0, 1, 3}

graph

Recommended Practice

Simple Approach: Create a recursive function that takes the current vertex, destination vertex, and the count of the vertex. Call the recursive function with all adjacent vertices of a current vertex with the value of k as k-1. When the value of k is 0, then check whether the current vertex is the destination or not. If destination, then the output answer is 1.

The following is the implementation of this simple solution.  

C++




// C++ program to count walks from u to
// v with exactly k edges
#include <iostream>
using namespace std;
 
// Number of vertices in the graph
#define V 4
 
// A naive recursive function to count
// walks from u to v with k edges
int countwalks(int graph[][V], int u, int v, int k)
{
    // Base cases
    if (k == 0 && u == v)
        return 1;
    if (k == 1 && graph[u][v])
        return 1;
    if (k <= 0)
        return 0;
 
    // Initialize result
    int count = 0;
 
    // Go to all adjacents of u and recur
    for (int i = 0; i < V; i++)
        if (graph[u][i] == 1) // Check if is adjacent of u
            count += countwalks(graph, i, v, k - 1);
 
    return count;
}
 
// driver program to test above function
int main()
{
    /* Let us create the graph shown in above diagram*/
    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;
}


Java




// Java program to count walks from u to v with exactly k edges
import java.util.*;
import java.lang.*;
import java.io.*;
 
class KPaths {
    static final int V = 4; // Number of vertices
 
    // A naive recursive function to count walks from u
    // to v with k edges
    int countwalks(int graph[][], int u, int v, int k)
    {
        // Base cases
        if (k == 0 && u == v)
            return 1;
        if (k == 1 && graph[u][v] == 1)
            return 1;
        if (k <= 0)
            return 0;
 
        // Initialize result
        int count = 0;
 
        // Go to all adjacents of u and recur
        for (int i = 0; i < V; i++)
            if (graph[u][i] == 1) // Check if is adjacent of u
                count += countwalks(graph, i, v, k - 1);
 
        return count;
    }
 
    // Driver method
    public static void main(String[] args) throws java.lang.Exception
    {
        /* Let us create the graph shown in above diagram*/
        int graph[][] = new int[][] { { 0, 1, 1, 1 },
                                      { 0, 0, 0, 1 },
                                      { 0, 0, 0, 1 },
                                      { 0, 0, 0, 0 } };
        int u = 0, v = 3, k = 2;
        KPaths p = new KPaths();
        System.out.println(p.countwalks(graph, u, v, k));
    }
} // Contributed by Aakash Hasija


Python3




# Python3 program to count walks from
# u to v with exactly k edges
 
# Number of vertices in the graph
V = 4
 
# A naive recursive function to count
# walks from u to v with k edges
def countwalks(graph, u, v, k):
 
    # Base cases
    if (k == 0 and u == v):
        return 1
    if (k == 1 and graph[u][v]):
        return 1
    if (k <= 0):
        return 0
     
    # Initialize result
    count = 0
     
    # Go to all adjacents of u and recur
    for i in range(0, V):
         
        # Check if is adjacent of u
        if (graph[u][i] == 1):
            count += countwalks(graph, i, v, k-1)
     
    return count
 
# Driver Code
 
# Let us create the graph shown in above diagram
graph = [[0, 1, 1, 1, ],
         [0, 0, 0, 1, ],
         [0, 0, 0, 1, ],
         [0, 0, 0, 0] ]
 
u = 0; v = 3; k = 2
print(countwalks(graph, u, v, k))
 
# This code is contributed by Smitha Dinesh Semwal.


C#




// C# program to count walks from u to
// v with exactly k edges
using System;
 
class GFG {
 
    // Number of vertices
    static int V = 4;
 
    // A naive recursive function to
    // count walks from u to v with
    // k edges
    static int countwalks(int[, ] graph, int u,
                          int v, int k)
    {
 
        // Base cases
        if (k == 0 && u == v)
            return 1;
        if (k == 1 && graph[u, v] == 1)
            return 1;
        if (k <= 0)
            return 0;
 
        // Initialize result
        int count = 0;
 
        // Go to all adjacents of u and recur
        for (int i = 0; i < V; i++)
 
            // Check if is adjacent of u
            if (graph[u, i] == 1)
                count += countwalks(graph, i, v, k - 1);
 
        return count;
    }
 
    // Driver method
    public static void Main()
    {
 
        /* Let us create the graph shown
        in above diagram*/
        int[, ] graph = new int[, ] { { 0, 1, 1, 1 },
                                      { 0, 0, 0, 1 },
                                      { 0, 0, 0, 1 },
                                      { 0, 0, 0, 0 } };
 
        int u = 0, v = 3, k = 2;
 
        Console.Write(
            countwalks(graph, u, v, k));
    }
}
 
// This code is contributed by nitin mittal.


PHP




<?php
// PHP program to count walks from u
// to v with exactly k edges
 
// Number of vertices in the graph
$V = 4;
 
// A naive recursive function to count
// walks from u to v with k edges
function countwalks( $graph, $u, $v, $k)
{
    global $V;
 
    // Base cases
    if ($k == 0 and $u == $v)
        return 1;
    if ($k == 1 and $graph[$u][$v])
        return 1;
    if ($k <= 0)        
        return 0;
     
    // Initialize result
    $count = 0;
     
    // Go to all adjacents of u and recur
    for ( $i = 0; $i < $V; $i++)
     
        // Check if is adjacent of u
        if ($graph[$u][$i] == 1)
            $count += countwalks($graph, $i,
                                $v, $k - 1);
     
    return $count;
}
 
    // Driver Code
    /* Let us create the graph
       shown in above diagram*/
    $graph = array(array(0, 1, 1, 1),
                   array(0, 0, 0, 1),
                   array(0, 0, 0, 1),
                   array(0, 0, 0, 0));
    $u = 0; $v = 3; $k = 2;
    echo countwalks($graph, $u, $v, $k);
 
// This code is contributed by anuj_67.
?>


Javascript




<script>
// Javascript program to count walks from u to
// v with exactly k edges
 
// Number of vertices in the graph
var V = 4
 
// A naive recursive function to count
// walks from u to v with k edges
function countwalks(graph, u, v, k)
{
    // Base cases
    if (k == 0 && u == v)
        return 1;
    if (k == 1 && graph[u][v])
        return 1;
    if (k <= 0)
        return 0;
 
    // Initialize result
    var count = 0;
 
    // Go to all adjacents of u and recur
    for (var i = 0; i < V; i++)
        if (graph[u][i] == 1) // Check if is adjacent of u
            count += countwalks(graph, i, v, k - 1);
 
    return count;
}
 
// driver program to test above function
/* Let us create the graph shown in above diagram*/
var graph = [[0, 1, 1, 1, ],
         [0, 0, 0, 1, ],
         [0, 0, 0, 1, ],
         [0, 0, 0, 0] ];
var u = 0, v = 3, k = 2;
document.write(countwalks(graph, u, v, k));
// This code contributed by shubhamsingh10
</script>


Output

2

Complexity Analysis: 

  • Time Complexity: O(Vk). 
    The worst-case time complexity of the above function is O(Vk) where V is the number of vertices in the given graph. We can simply analyze the time complexity by drawing a recursion tree. The worst occurs for a complete graph. In the worst case, every internal node of the recursion tree would have exactly n children.
  • Auxiliary Space: O(V). 
    To store the stack space and the visited array O(V) space is needed.

Efficient Approach: The solution can be optimized using Dynamic Programming. The idea is to build a 3D table where the first dimension is the source, the second dimension is the destination, the third dimension is the number of edges from source to destination, and the value is the count of walks. Like others, Dynamic Programming problems, fill the 3D table in a bottom-up manner. 

C++




// C++ program to count walks from
// u to v with exactly k edges
#include <iostream>
using namespace std;
 
// Number of vertices in the graph
#define V 4
 
// A Dynamic programming based function to count walks from u
// to v with k edges
int countwalks(int graph[][V], int u, int v, int k)
{
    // Table to be filled up using DP.
    // The value count[i][j][e] will
    // store count of possible walks from
    // i to j with exactly k edges
    int count[V][V][k + 1];
 
    // Loop for number of edges from 0 to k
    for (int e = 0; e <= k; e++) {
        for (int i = 0; i < V; i++) // for source
        {
            for (int j = 0; j < V; j++) // for destination
            {
                // initialize value
                count[i][j][e] = 0;
 
                // from base cases
                if (e == 0 && i == j)
                    count[i][j][e] = 1;
                if (e == 1 && graph[i][j])
                    count[i][j][e] = 1;
 
                // go to adjacent only when the
                // number of edges is more than 1
                if (e > 1) {
                    for (int a = 0; a < V; a++) // adjacent of source i
                        if (graph[i][a])
                            count[i][j][e] += count[a][j][e - 1];
                }
            }
        }
    }
    return count[u][v][k];
}
 
// driver program to test above function
int main()
{
    /* Let us create the graph shown in above diagram*/
    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;
}


Java




// Java program to count walks from
// u to v with exactly k edges
import java.util.*;
import java.lang.*;
import java.io.*;
 
class KPaths {
    static final int V = 4; // Number of vertices
 
    // A Dynamic programming based function to count walks from u
    // to v with k edges
    int countwalks(int graph[][], int u, int v, int k)
    {
        // Table to be filled up using DP. The value count[i][j][e]
        // will/ store count of possible walks from i to j with
        // exactly k edges
        int count[][][] = new int[V][V][k + 1];
 
        // Loop for number of edges from 0 to k
        for (int e = 0; e <= k; e++) {
            for (int i = 0; i < V; i++) // for source
            {
                for (int j = 0; j < V; j++) // for destination
                {
                    // initialize value
                    count[i][j][e] = 0;
 
                    // from base cases
                    if (e == 0 && i == j)
                        count[i][j][e] = 1;
                    if (e == 1 && graph[i][j] != 0)
                        count[i][j][e] = 1;
 
                    // go to adjacent only when number of edges
                    // is more than 1
                    if (e > 1) {
                        for (int a = 0; a < V; a++) // adjacent of i
                            if (graph[i][a] != 0)
                                count[i][j][e] += count[a][j][e - 1];
                    }
                }
            }
        }
        return count[u][v][k];
    }
 
    // Driver method
    public static void main(String[] args) throws java.lang.Exception
    {
        /* Let us create the graph shown in above diagram*/
        int graph[][] = new int[][] { { 0, 1, 1, 1 },
                                      { 0, 0, 0, 1 },
                                      { 0, 0, 0, 1 },
                                      { 0, 0, 0, 0 } };
        int u = 0, v = 3, k = 2;
        KPaths p = new KPaths();
        System.out.println(p.countwalks(graph, u, v, k));
    }
} // Contributed by Aakash Hasija


Python3




# Python3 program to count walks from
# u to v with exactly k edges
 
# Number of vertices
V = 4
 
# A Dynamic programming based function
# to count walks from u to v with k edges
 
 
def countwalks(graph, u, v, k):
 
    # Table to be filled up using DP.
    # The value count[i][j][e] will/
    # store count of possible walks
    # from i to j with exactly k edges
    count = [[[0 for k in range(k + 1)]
              for i in range(V)]
             for j in range(V)]
 
    # Loop for number of edges from 0 to k
    for e in range(0, k + 1):
        # For Source
        for i in range(V):
            # For Destination
            for j in range(V):
                # Initialize value
                # count[i][j][e] = 0
 
                # From base cases
                if (e == 0 and i == j):
                    count[i][j][e] = 1
                if (e == 1 and graph[i][j] != 0):
                    count[i][j][e] = 1
 
                # Go to adjacent only when number
                # of edges is more than 1
                if (e > 1):
 
                    for a in range(V):
 
                        # Adjacent of i
                        if (graph[i][a] != 0):
                            count[i][j][e] += count[a][j][e - 1]
 
    return count[u][v][k]
 
 
# Driver code
if __name__ == '__main__':
 
    # Let us create the graph shown
    # in above diagram
    graph = [[0, 1, 1, 1],
             [0, 0, 0, 1],
             [0, 0, 0, 1],
             [0, 0, 0, 0]]
 
    u = 0
    v = 3
    k = 2
 
    print(countwalks(graph, u, v, k))
 
# This code is contributed by Rajput-Ji


C#




// C# program to count walks from u to v
// with exactly k edges
using System;
 
class GFG {
    static int V = 4; // Number of vertices
 
    // A Dynamic programming based function
    // to count walks from u to v with k edges
    static int countwalks(int[, ] graph, int u,
                          int v, int k)
    {
        // Table to be filled up using DP. The
        // value count[i][j][e] will/ store
        // count of possible walks from i to
        // j with exactly k edges
        int[,, ] count = new int[V, V, k + 1];
 
        // Loop for number of edges from 0 to k
        for (int e = 0; e <= k; e++) {
 
            // for source
            for (int i = 0; i < V; i++) {
 
                // for destination
                for (int j = 0; j < V; j++) {
                    // initialize value
                    count[i, j, e] = 0;
 
                    // from base cases
                    if (e == 0 && i == j)
                        count[i, j, e] = 1;
                    if (e == 1 && graph[i, j] != 0)
                        count[i, j, e] = 1;
 
                    // go to adjacent only when
                    // number of edges
                    // is more than 1
                    if (e > 1) {
                        // adjacent of i
                        for (int a = 0; a < V; a++)
                            if (graph[i, a] != 0)
                                count[i, j, e] += count[a, j, e - 1];
                    }
                }
            }
        }
 
        return count[u, v, k];
    }
 
    // Driver method
    public static void Main()
    {
        /* Let us create the graph shown in
        above diagram*/
        int[, ] graph = { { 0, 1, 1, 1 },
                          { 0, 0, 0, 1 },
                          { 0, 0, 0, 1 },
                          { 0, 0, 0, 0 } };
        int u = 0, v = 3, k = 2;
 
        Console.WriteLine(
            countwalks(graph, u, v, k));
    }
}
 
// This is Code Contributed by anuj_67.


Javascript




<script>
 
// Javascript program to count walks from
// u to v with exactly k edges
 
// Number of vertices in the graph
var V = 4
 
// A Dynamic programming based function to count walks from u
// to v with k edges
function countwalks(graph, u, v, k)
{
    // Table to be filled up using DP.
    // The value count[i][j][e] will
    // store count of possible walks from
    // i to j with exactly k edges
    var count = new Array(V);
    for (var i = 0; i <V; i++) {
        count[i] = new Array(V);
        for (var j = 0; j < V; j++) {
            count[i][j] = new Array(V);
            for (var e = 0; e <= k; e++) {
                count[i][j][e] = 0;
            }
        }
    }
 
    // Loop for number of edges from 0 to k
    for (var e = 0; e <= k; e++) {
        for (var i = 0; i < V; i++) // for source
        {
            for (var j = 0; j < V; j++) // for destination
            {
                // initialize value
                count[i][j][e] = 0;
 
                // from base cases
                if (e == 0 && i == j)
                    count[i][j][e] = 1;
                if (e == 1 && graph[i][j])
                    count[i][j][e] = 1;
 
                // go to adjacent only when the
                // number of edges is more than 1
                if (e > 1) {
                    for (var a = 0; a < V; a++) // adjacent of source i
                        if (graph[i][a])
                            count[i][j][e] += count[a][j][e - 1];
                }
            }
        }
    }
    return count[u][v][k];
}
 
// driver program to test above function
/* Let us create the graph shown in above diagram*/
var graph = [ [ 0, 1, 1, 1 ],
              [ 0, 0, 0, 1 ],
              [ 0, 0, 0, 1 ],
              [ 0, 0, 0, 0 ] ];
var u = 0, v = 3, k = 2;
document.write(countwalks(graph, u, v, k));
 
// This code is contributed by ShubhamSingh10
</script>


PHP




<?php
// PHP program to count walks from
// u to v with exactly k edges
 
// Number of vertices in the graph
define('V', 4);
 
// A Dynamic programming based function to count walks from u
// to v with k edges
function countwalks($graph, $u, $v, $k)
{
    // Table to be filled up using DP.
    // The value count[i][j][e] will
    // store count of possible walks from
    // i to j with exactly k edges
    $count = array();
    for ($i = 0; $i < V; $i++) {
        for ($j = 0; $j < V; $j++) {
            for ($e = 0; $e <= $k; $e++) {
                $count[$i][$j][$e] = 0;
            }
        }
    }
 
    // Loop for number of edges from 0 to k
    for ($e = 0; $e <= $k; $e++) {
        for ($i = 0; $i < V; $i++) // for source
        {
            for ($j = 0; $j < V; $j++) // for destination
            {
                // initialize value
                $count[$i][$j][$e] = 0;
 
                // from base cases
                if ($e == 0 && $i == $j)
                    $count[$i][$j][$e] = 1;
                if ($e == 1 && $graph[$i][$j])
                    $count[$i][$j][$e] = 1;
 
                // go to adjacent only when the
                // number of edges is more than 1
                if ($e > 1) {
                    for ($a = 0; $a < V; $a++) // adjacent of source i
                        if ($graph[$i][$a])
                            $count[$i][$j][$e] += $count[$a][$j][$e - 1];
                }
            }
        }
    }
    return $count[$u][$v][$k];
}
 
// driver program to test above function
/* Let us create the graph shown in above diagram*/
$graph = array(array(0, 1, 1, 1),
                array(0, 0, 0, 1),
                array(0, 0, 0, 1),
                array(0, 0, 0, 0));
 
$u = 0;
$v = 3;
$k = 2;
echo countwalks($graph, $u, $v, $k);
 
// This code is contributed by rajsanghavi9.
?>


Output

2

Complexity Analysis: 

  • Time Complexity: O(V3). 
    Three nested loops are needed to fill the DP table, so the time complexity is O(V3).
  • Auxiliary Space: O(V2K). 
    To store the DP table O(V2K) space is needed.

We can also use Divide and Conquer to solve the above problem in O(V3Logk) time. The count of walks of length k from u to v is the [u][v]’th entry in (graph[V][V])k. We can calculate the power by doing O(Logk) multiplication by using the divide and conquer technique to calculate power. A multiplication between two matrices of size V x V takes O(V3) time. 



Previous Article
Next Article

Similar Reads

Number of Walks from source to destination
Given a graph and two vertices src and dest, count the total number of paths from src to dest where the length of the path is k (there should be exactly k edges between them). Note that the graph is represented as an adjacency matrix.For example, consider the following graph: The number of paths from vertex 0 to vertex 3 with length 2 is 2 ({0-&gt;
1 min read
Shortest path in a graph from a source S to destination D with exactly K edges for multiple Queries
Given a graph with N nodes, a node S and Q queries each consisting of a node D and K, the task is to find the shortest path consisting of exactly K edges from node S to node D for each query. If no such path exists then print -1. Note: K will always be lesser than 2 * N. Examples: Input: N = 3, edges[][] = {{1, 2, 5}, {2, 3, 3}, {3, 1, 4}}, S = 1,
8 min read
Shortest Path with even number of Edges from Source to Destination
Given an undirected graph G, the task is to find the shortest path of even-length, given 1 as Source Node and N as Destination Node. Path length refers to the number of edges present in a path (not the cost of the path). Examples: Input: N = 5, G is given below: Output: 10 Explanation: All paths from 1(source node) to 5 (destination node) are: 1-
13 min read
Minimum edges to reverse to make path from a source to a destination
Given a directed graph and a source node and destination node, we need to find how many edges we need to reverse in order to make at least 1 path from the source node to the destination node. Examples: In above graph there were two paths from node 0 to node 6, 0 -&gt; 1 -&gt; 2 -&gt; 3 -&gt; 6 0 -&gt; 1 -&gt; 5 -&gt; 4 -&gt; 6 But for first path on
15+ min read
Count all possible paths from source to destination in given 3D array
Given three integers M, N and K, the task is to count all the possible paths from the cell (0, 0, 0) to cell (M-1, N-1, K-1) in a matrix of size (M, N, K). Movement is allowed only in three directions, which are along the positive direction of the three axes i.e. from any cell (i, j, k) movement is allowed to cells (i+1, j, k), (i, j+1, k) and (i,
12 min read
Count of possible hexagonal walks
We are given an infinite two dimensional plane made of hexagons connected together. We can visualize this plane as a honeycomb. Element X is present on one of the cells / hexagon. We are given N steps, the task is to calculate number of such hexagonal paths possible in which element X has to perform a walk of N steps and return back to the original
8 min read
Count of all unique paths from given source to destination in a Matrix
Given a 2D matrix of size n*m, a source ‘s’ and a destination ‘d’, print the count of all unique paths from given ‘s’ to ‘d’. From each cell, you can either move only to the right or down. Examples: Input: arr[][] = { {1, 2, 3}, {4, 5, 6} }, s = {0, 0}, d = {1, 2}Output: 3Explanation: All possible paths from source to destination are: 1 -&gt; 4 -
4 min read
Count the number of walks of length N where cost of each walk is equal to a given number
Given a weighted undirected graph, Length of walks N and Cost X. The task is to count the number of different walks W of length N such that Cost(W) = X.We define the cost of a walk W, as the maximum over the weights of the edges along the walk.The nodes are numbered from 1 to n. The graph does not contain any multiple edges or self-loops. Examples:
10 min read
Count total ways to reach destination from source in an undirected Graph
Given an undirected graph, a source vertex ‘s’ and a destination vertex ‘d’, the task is to count the total paths from the given ‘s’ to ‘d’. Examples Input: s = 1, d = 4 Output: 2 Explanation: Below are the 2 paths from 1 to 4 1 -&gt; 3 -&gt; 4 1 -&gt; 2 -&gt; 3 -&gt; 4 Input: s = 3, d = 9 Output: 6 Explanation: Below are the 6 paths from 3 to 9 3
12 min read
Minimum time required to transport all the boxes from source to the destination under the given constraints
Given two arrays, box[] and truck[], where box[i] represents the weight of the ith box and truck[i] represents the maximum load that the ith truck can carry. Now each truck takes 1 hour to transport a box from source to destination and another one hour to come back. Now, given that all the boxes are kept at the source, the task is to find the minim
10 min read
three90RightbarBannerImg