Open In App

Count all possible Paths between two Vertices

Last Updated : 28 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Count the total number of ways or paths that exist between two vertices in a directed graph. These paths don’t contain a cycle, the simple enough reason is that a cycle contains an infinite number of paths and hence they create a problem

Examples: 

For the following Graph:

  

Input: Count paths between A and E
Output: Total paths between A and E are 4
Explanation: The 4 paths between A and E are:

                      A -> E
                      A -> B -> E
                      A -> C -> E
                      A -> B -> D -> C -> E 

Input: Count paths between A and C
Output: Total paths between A and C are 2
Explanation: The 2 paths between A and C are:

                      A -> C
                      A -> B -> D -> C

Count paths between two vertices using Backtracking

To solve the problem follow the below idea:

The problem can be solved using backtracking, which says to take a path and start walking on it and check if it leads us to the destination vertex then count the path and backtrack to take another path. If the path doesn’t lead to the destination vertex, discard the path. This type of graph traversal is called Backtracking.

Backtracking for the above graph can be shown like this: 

Note: The red color vertex is the source vertex and the light-blue color vertex is destination, rest are either intermediate or discarded paths. 
 

This give four paths between source(A) and destination(E) vertex

Why this solution will not work for a graph which contains cycles? 

The Problem Associated with this is that now if one more edge is added between C and B, it would make a cycle (B -> D -> C -> B). And hence after every cycle through the loop, the length path will increase and that will be considered a different path, and there would be infinitely many paths because of the cycle
 

Follow the given steps to solve the problem:

  • Create a recursive function that takes the index of a node of a graph and the destination index. Keep a global or a static variable count to store the count. 
  • Keep a record of the nodes visited using a visited array and while returning mark the current node to be unvisited to discover other paths.
    • If the current node is the destination then increase the count.
    • Else for all the adjacent nodes, i.e. nodes that are accessible from the current node, call the recursive function with the index of the adjacent node and the destination.
  • Print the Count as the required answer.

Below is the implementation of the above approach.

C++




/*
 * C++ program to count all paths from a source to a
 * destination.
 * Note that the original example has been refactored.
 */
#include <bits/stdc++.h>
using namespace std;
 
/*
 * A directed graph using adjacency list representation;
 * every vertex holds a list of all neighbouring vertices
 * that can be reached from it.
 */
class Graph {
public:
    // Construct the graph given the number of vertices...
    Graph(int vertices);
    // Specify an edge between two vertices
    void add_edge(int src, int dst);
    // Call the recursive helper function to count all the
    // paths
    int count_paths(int src, int dst, int vertices);
 
private:
    int m_vertices;
    list<int>* m_neighbours;
    void path_counter(int src, int dst, int& path_count,
                      vector<bool>& visited);
};
 
Graph::Graph(int vertices)
{
    m_vertices = vertices; // unused!!
    /* An array of linked lists - each element corresponds
    to a vertex and will hold a list of neighbours...*/
    m_neighbours = new list<int>[vertices];
}
 
void Graph::add_edge(int src, int dst)
{
    m_neighbours[src].push_back(dst);
}
 
int Graph::count_paths(int src, int dst, int vertices)
{
    int path_count = 0;
    vector<bool> visited(vertices, false);
    path_counter(src, dst, path_count, visited);
    return path_count;
}
 
/*
 * A recursive function that counts all paths from src to
 * dst. Keep track of the count in the parameter.
 */
void Graph::path_counter(int src, int dst, int& path_count,
                         vector<bool>& visited)
{
    // If we've reached the destination, then increment
    // count...
    visited[src] = true;
    if (src == dst) {
        path_count++;
    }
    // ...otherwise recurse into all neighbours...
    else {
        for (auto neighbour : m_neighbours[src]) {
            if (!visited[neighbour])
                path_counter(neighbour, dst, path_count,
                             visited);
        }
    }
    visited[src] = false;
}
 
// Driver code
int main()
{
    // Create a graph given in the above diagram - see link
    Graph g(5);
    g.add_edge(0, 1);
    g.add_edge(0, 2);
    g.add_edge(0, 4);
    g.add_edge(1, 3);
    g.add_edge(1, 4);
    g.add_edge(2, 3);
    g.add_edge(2, 1);
    g.add_edge(3, 2);
     
      // Function call
    cout << g.count_paths(0, 4, 5);
 
    return 0;
}


Java




// Java program to count all paths from a source
// to a destination
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
 
// This class represents a directed graph using
// adjacency list representation
 
class Graph {
 
    // No. of vertices
    private int V;
 
    // Array of lists for
    // Adjacency List
    // Representation
    private LinkedList<Integer> adj[];
 
    @SuppressWarnings("unchecked") Graph(int v)
    {
        V = v;
        adj = new LinkedList[v];
        for (int i = 0; i < v; ++i)
            adj[i] = new LinkedList<>();
    }
 
    // Method to add an edge into the graph
    void addEdge(int v, int w)
    {
 
        // Add w to v's list.
        adj[v].add(w);
    }
 
    // A recursive method to count
    // all paths from 'u' to 'd'.
    int countPathsUtil(int u, int d, int pathCount)
    {
 
        // If current vertex is same as
        // destination, then increment count
        if (u == d) {
            pathCount++;
        }
 
        // Recur for all the vertices
        // adjacent to this vertex
        else {
            Iterator<Integer> i = adj[u].listIterator();
            while (i.hasNext()) {
                int n = i.next();
                pathCount = countPathsUtil(n, d, pathCount);
            }
        }
        return pathCount;
    }
 
    // Returns count of
    // paths from 's' to 'd'
    int countPaths(int s, int d)
    {
 
        // Call the recursive method
        // to count all paths
        int pathCount = 0;
        pathCount = countPathsUtil(s, d, pathCount);
        return pathCount;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        Graph g = new Graph(5);
        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(0, 3);
        g.addEdge(1, 3);
        g.addEdge(2, 3);
        g.addEdge(1, 4);
        g.addEdge(2, 4);
 
        int s = 0, d = 3;
       
          // Function call
        System.out.println(g.countPaths(s, d));
    }
}
 
// This code is contributed by shubhamjd.


Python3




# Python 3 program to count all paths
# from a source to a destination.
 
# A directed graph using adjacency
# list representation
 
 
class Graph:
 
    def __init__(self, V):
        self.V = V
        self.adj = [[] for i in range(V)]
 
    def addEdge(self, u, v):
 
        # Add v to u’s list.
        self.adj[u].append(v)
 
    # Returns count of paths from 's' to 'd'
    def countPaths(self, s, d):
 
        # Mark all the vertices
        # as not visited
        visited = [False] * self.V
 
        # Call the recursive helper
        # function to print all paths
        pathCount = [0]
        self.countPathsUtil(s, d, visited, pathCount)
        return pathCount[0]
 
    # A recursive function to print all paths
    # from 'u' to 'd'. visited[] keeps track
    # of vertices in current path. path[]
    # stores actual vertices and path_index
    # is current index in path[]
    def countPathsUtil(self, u, d,
                       visited, pathCount):
        visited[u] = True
 
        # If current vertex is same as
        # destination, then increment count
        if (u == d):
            pathCount[0] += 1
 
        # If current vertex is not destination
        else:
 
            # Recur for all the vertices
            # adjacent to current vertex
            i = 0
            while i < len(self.adj[u]):
                if (not visited[self.adj[u][i]]):
                    self.countPathsUtil(self.adj[u][i], d,
                                        visited, pathCount)
                i += 1
 
        visited[u] = False
 
 
# Driver Code
if __name__ == '__main__':
 
    # Create a graph given in the
    # above diagram
    g = Graph(4)
    g.addEdge(0, 1)
    g.addEdge(0, 2)
    g.addEdge(0, 3)
    g.addEdge(2, 0)
    g.addEdge(2, 1)
    g.addEdge(1, 3)
 
    s = 2
    d = 3
     
    # Function call
    print(g.countPaths(s, d))
 
# This code is contributed by PranchalK


C#




// C# program to count all paths from a source
// to a destination.
using System;
using System.Collections.Generic;
 
// This class represents a directed graph using
// adjacency list representation
public class Graph {
 
    // Array of lists for
    // Adjacency List
    // Representation
    private List<int>[] adj;
 
    Graph(int v)
    {
        adj = new List<int>[ v ];
        for (int i = 0; i < v; ++i)
            adj[i] = new List<int>();
    }
 
    // Method to add an edge into the graph
    void addEdge(int v, int w)
    {
 
        // Add w to v's list.
        adj[v].Add(w);
    }
 
    // A recursive method to count
    // all paths from 'u' to 'd'.
    int countPathsUtil(int u, int d, int pathCount)
    {
 
        // If current vertex is same as
        // destination, then increment count
        if (u == d) {
            pathCount++;
        }
 
        // Recur for all the vertices
        // adjacent to this vertex
        else {
            foreach(int i in adj[u])
            {
                int n = i;
                pathCount = countPathsUtil(n, d, pathCount);
            }
        }
        return pathCount;
    }
 
    // Returns count of
    // paths from 's' to 'd'
    int countPaths(int s, int d)
    {
 
        // Call the recursive method
        // to count all paths
        int pathCount = 0;
        pathCount = countPathsUtil(s, d, pathCount);
        return pathCount;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        Graph g = new Graph(5);
        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(0, 3);
        g.addEdge(1, 3);
        g.addEdge(2, 3);
        g.addEdge(1, 4);
        g.addEdge(2, 4);
 
        int s = 0, d = 3;
       
          // Function call
        Console.WriteLine(g.countPaths(s, d));
    }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// JavaScript program to count all paths from a source
// to a destination.
 
// No. of vertices
let  V;
 
// Array of lists for
    // Adjacency List
    // Representation
let adj;
 
function Graph(v)
{
    V = v;
        adj = new Array(v);
        for (let i = 0; i < v; ++i)
            adj[i] = [];
}
 
// Method to add an edge into the graph
function addEdge(v,w)
{
    // Add w to v's list.
        adj[v].push(w);
}
 
// A recursive method to count
    // all paths from 'u' to 'd'.
function countPathsUtil(u,d,pathCount)
{
    // If current vertex is same as
        // destination, then increment count
        if (u == d) {
            pathCount++;
        }
  
        // Recur for all the vertices
        // adjacent to this vertex
        else {
             
            for(let i=0;i<adj[u].length;i++) {
                let n = adj[u][i];
                pathCount = countPathsUtil(n, d, pathCount);
            }
        }
        return pathCount;
}
 
// Returns count of
    // paths from 's' to 'd'
function countPaths(s,d)
{
    // Call the recursive method
        // to count all paths
        let pathCount = 0;
        pathCount = countPathsUtil(s, d,
                                   pathCount);
        return pathCount;
}
 
 // Driver Code
Graph(5);
addEdge(0, 1);
addEdge(0, 2);
addEdge(0, 3);
addEdge(1, 3);
addEdge(2, 3);
addEdge(1, 4);
addEdge(2, 4);
 
let s = 0, d = 3;
document.write(countPaths(s, d));
 
 
// This code is contributed by avanitrachhadiya2155
 
</script>


Output

3

Time Complexity: O(2^n), where n is the number of vertices in the graph. This is because in the worst case scenario, the program will have to recursively visit all possible paths from the source to the destination, which can be exponential in the number of vertices.
Auxiliary Space: O(N), Auxiliary stack space used by recursion calls



Previous Article
Next Article

Similar Reads

Find the remaining vertices of a square from two given vertices
Given the coordinates of any two vertices of a square (X1, Y1) and (X2, Y2), the task is to find the coordinates of the other two vertices. If a square cannot be formed using these two vertices, print -1. Examples: Input: X1 = 1, Y1 = 2, X2 = 3, Y2 = 4 Output: (1, 4), (3, 2) Explanation: From the above figure the other two vertices of the square wi
6 min read
Find three vertices in an N-sided regular polygon such that the angle subtended at a vertex by two other vertices is closest to A
Given an N-sided regular convex polygon and an angle A in degrees, the task is to find any 3 vertices i, j, and k, such that the angle subtended at vertex j by vertex i and k is closest to A. Note: Each vertex is numbered from 1 to N in an anticlockwise direction starting from any vertex. Examples: Input: N = 3, A = 15Output: 2 1 3Explanation:The g
7 min read
Find maximum number of edge disjoint paths between two vertices
Given a directed graph and two vertices in it, source 's' and destination 't', find out the maximum number of edge disjoint paths from s to t. Two paths are said edge disjoint if they don't share any edge. There can be maximum two edge disjoint paths from source 0 to destination 7 in the above graph. Two edge disjoint paths are highlighted below in
15+ min read
Construct a graph using N vertices whose shortest distance between K pair of vertices is 2
Given two positive integers N and K, the task is to construct a simple and connected graph consisting of N vertices with the length of each edge as 1 unit, such that the shortest distance between exactly K pairs of vertices is 2. If it is not possible to construct the graph, then print -1. Otherwise, print the edges of the graph. Examples: Input: N
7 min read
Shortest paths from all vertices to a destination
Given a Weighted Directed Graph and a destination vertex in the graph, find the shortest distance from all vertex to the destination vertex.Input : Output : 0 6 10 7 5Distance of 0 from 0: 0 Distance of 0 from 1: 1+5 = 6 (1-&gt;4-&gt;0) Distance of 0 from 2: 10 (2-&gt;0) Distance of 0 from 3: 1+1+5 = 7 (3-&gt;1-&gt;4-&gt;0) Distance of 0 from 4: 5
11 min read
How to find Shortest Paths from Source to all Vertices using Dijkstra's Algorithm
Given a weighted graph and a source vertex in the graph, find the shortest paths from the source to all the other vertices in the given graph. Note: The given graph does not contain any negative edge. Examples: Input: src = 0, the graph is shown below. Output: 0 4 12 19 21 11 9 8 14Explanation: The distance from 0 to 1 = 4.The minimum distance from
15+ min read
Find K vertices in the graph which are connected to at least one of remaining vertices
Given a connected graph with N vertices. The task is to select k(k must be less than or equals to n/2, not necessarily minimum) vertices from the graph such that all these selected vertices are connected to at least one of the non selected vertex. In case of multiple answers print any one of them. Examples: Input : Output : 1 Vertex 1 is connected
8 min read
Maximize the number of uncolored vertices appearing along the path from root vertex and the colored vertices
Given a tree with N vertices numbered 1 through N with vertex 1 as root vertex and N - 1 edges. We have to color exactly k number of vertices and count the number of uncolored vertices between root vertex and every colored vertex. We have to include the root vertex in the count if it is not colored. The task to maximize the number of uncolored vert
8 min read
Pendant Vertices, Non-Pendant Vertices, Pendant Edges and Non-Pendant Edges in Graph
Pre-requisites: Handshaking theorem. Pendant Vertices Let G be a graph, A vertex v of G is called a pendant vertex if and only if v has degree 1. In other words, pendant vertices are the vertices that have degree 1, also called pendant vertex. Note: Degree = number of edges connected to a vertex In the case of trees, a pendant vertex is known as a
7 min read
Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths
Given a matrix mat[][] with N rows and M columns. The task is to find the minimum number of changes required in the matrix such that every path from top left to bottom right is a palindromic path. In a path only right and bottom movements are allowed from one cell to another cell.Examples: Input: mat[][] = {{1, 2}, {3, 1}} Output: 0 Explanation: Ev
15+ min read
Article Tags :
Practice Tags :