Open In App

Count all possible Paths between two Vertices

Last Updated : 25 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Directed Graph with n vertices represented as a list of directed edges represented by a 2D array edgeList[][], where each edge is defined as (u, v) meaning there is a directed edge from u to v. Additionally, you are given two vertices: source and destination.
The task is to determine the total number of distinct simple paths (i.e., paths that do not contain any cycles) from the source vertex to the destination vertex.
Note: Only acyclic (simple) paths are considered. Paths containing cycles are excluded, as they can lead to an infinite number of paths.

Examples: 

ss


Input: n = 5, edgeList[][] = [[A, B], [A, C], [A, E], [B, E], [B, D], [C, E], [D, C]], source = A, destination = D
Output: 4
Explanation: The 4 paths between A and E are:

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

Input: n = 5, edgeList[][] = [[A, B], [A, C], [A, E], [B, E], [B, D], [C, E], [D, C]], source = A, destination = C
Output: 2
Explanation: The 2 paths between A and C are:

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

[Approach - 1] Using Depth-First Search - O(2^n) Time and O(n) Space

The idea is to count all unique paths from a given source to a destination in a directed graph using Depth First Search (DFS). The thought process is to recursively explore all possible paths by visiting unvisited neighbors and backtrack to try alternative routes. We observe that since the graph is directed, we only follow edges in their specified direction, and we use a visited array to avoid revisiting nodes in the current path. The approach ensures that each valid path to the destination is counted exactly once by incrementing the count only when the base case node == dest is met.

Depth-First Search 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 approach 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
 


Steps to implement the above idea:

  • Start by building an adjacency list to represent the directed connections between nodes.
  • Prepare a boolean array to keep track of which nodes have already been visited in the current path.
  • Define a recursive function that explores all outgoing paths from the current node toward the target node.
  • If the current node matches the destination node, increment the total and return immediately.
  • For each connected node that hasn't been visited, recursively explore it as the next step in the path.
  • After returning from a recursive call, unmark the node to allow its reuse in other possible paths.
  • Invoke the recursive traversal from the source node and return the final count of all valid paths.
C++
// C++ Code to find count of paths between 
// two vertices of a directed graph using DFS 
#include <bits/stdc++.h>
using namespace std;

void dfs(int node, int dest, vector<vector<int>> &graph,
         vector<bool> &visited, int &count) {
    
    // If destination is reached, 
    // increment count
    if (node == dest) {
        count++;
        return;
    }

    // Mark current node as visited
    visited[node] = true;

    // Explore all unvisited neighbors
    for (int neighbor : graph[node]) {
        if (!visited[neighbor]) {
            dfs(neighbor, dest, graph, visited, count);
        }
    }

    // Backtrack: unmark the node 
    // before returning
    visited[node] = false;
}

int countPaths(int n, vector<vector<int>> &edgeList,
               int source, int destination) {

    // Create adjacency list(1 - based indexing)
    vector<vector<int>> graph(n + 1); 
    for (auto &edge : edgeList) {
        int u = edge[0];
        int v = edge[1];
        graph[u].push_back(v);
    }

    // Track visited nodes
    vector<bool> visited(n + 1, false);
    int count = 0;

    // Start DFS from source
    dfs(source, destination, graph, visited, count);

    return count;
}

int main() {
    
    int n = 5;

    // Edge list: [u, v] represents u -> v
    vector<vector<int>> edgeList = {
        {1, 2}, {1, 3}, {1, 5},
        {2, 5}, {2, 4}, {3, 5}, {4, 3}
    };

    int source = 1;
    int destination = 5;

    cout << countPaths(n, edgeList, source, destination);

    return 0;
}
Java
// Java Code to find count of paths between 
// two vertices of a directed graph using DFS 
import java.util.*;

class GfG {

    static void dfs(int node, int dest, List<List<Integer>> graph,
                    boolean[] visited, int[] count) {

        // If destination is reached, 
        // increment count
        if (node == dest) {
            count[0]++;
            return;
        }

        // Mark current node as visited
        visited[node] = true;

        // Explore all unvisited neighbors
        for (int neighbor : graph.get(node)) {
            if (!visited[neighbor]) {
                dfs(neighbor, dest, graph, visited, count);
            }
        }

        // Backtrack: unmark the node 
        // before returning
        visited[node] = false;
    }

    static int countPaths(int n, int[][] edgeList,
                          int source, int destination) {

        // Create adjacency list(1 - based indexing)
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i <= n; i++) {
            graph.add(new ArrayList<>());
        }

        for (int[] edge : edgeList) {
            int u = edge[0];
            int v = edge[1];
            graph.get(u).add(v);
        }

        // Track visited nodes
        boolean[] visited = new boolean[n + 1];
        int[] count = new int[1];

        // Start DFS from source
        dfs(source, destination, graph, visited, count);

        return count[0];
    }

    public static void main(String[] args) {

        int n = 5;

        // Edge list: [u, v] represents u -> v
        int[][] edgeList = {
            {1, 2}, {1, 3}, {1, 5},
            {2, 5}, {2, 4}, {3, 5}, {4, 3}
        };

        int source = 1;
        int destination = 5;

        System.out.println(countPaths(n, edgeList, source, destination));
    }
}
Python
# Python Code to find count of paths between 
# two vertices of a directed graph using DFS 
def dfs(node, dest, graph, visited, count):

    # If destination is reached, 
    # increment count
    if node == dest:
        count[0] += 1
        return

    # Mark current node as visited
    visited[node] = True

    # Explore all unvisited neighbors
    for neighbor in graph[node]:
        if not visited[neighbor]:
            dfs(neighbor, dest, graph, visited, count)

    # Backtrack: unmark the node 
    # before returning
    visited[node] = False

def countPaths(n, edgeList, source, destination):

    # Create adjacency list(1 - based indexing)
    graph = [[] for _ in range(n + 1)]
    for u, v in edgeList:
        graph[u].append(v)

    # Track visited nodes
    visited = [False] * (n + 1)
    count = [0]

    # Start DFS from source
    dfs(source, destination, graph, visited, count)

    return count[0]

if __name__ == "__main__":

    n = 5

    # Edge list: [u, v] represents u -> v
    edgeList = [
        [1, 2], [1, 3], [1, 5],
        [2, 5], [2, 4], [3, 5], [4, 3]
    ]

    source = 1
    destination = 5

    print(countPaths(n, edgeList, source, destination))
C#
// C# Code to find count of paths between 
// two vertices of a directed graph using DFS 
using System;
using System.Collections.Generic;

class GfG {

    static void dfs(int node, int dest, List<List<int>> graph,
                    bool[] visited, ref int count) {

        // If destination is reached, 
        // increment count
        if (node == dest) {
            count++;
            return;
        }

        // Mark current node as visited
        visited[node] = true;

        // Explore all unvisited neighbors
        foreach (int neighbor in graph[node]) {
            if (!visited[neighbor]) {
                dfs(neighbor, dest, graph, visited, ref count);
            }
        }

        // Backtrack: unmark the node 
        // before returning
        visited[node] = false;
    }

    static int countPaths(int n, int[][] edgeList,
                          int source, int destination) {

        // Create adjacency list(1 - based indexing)
        List<List<int>> graph = new List<List<int>>();
        for (int i = 0; i <= n; i++) {
            graph.Add(new List<int>());
        }

        foreach (int[] edge in edgeList) {
            int u = edge[0];
            int v = edge[1];
            graph[u].Add(v);
        }

        // Track visited nodes
        bool[] visited = new bool[n + 1];
        int count = 0;

        // Start DFS from source
        dfs(source, destination, graph, visited, ref count);

        return count;
    }

    static void Main() {

        int n = 5;

        // Edge list: [u, v] represents u -> v
        int[][] edgeList = {
            new int[]{1, 2}, new int[]{1, 3}, new int[]{1, 5},
            new int[]{2, 5}, new int[]{2, 4}, new int[]{3, 5}, new int[]{4, 3}
        };

        int source = 1;
        int destination = 5;

        Console.WriteLine(countPaths(n, edgeList, source, destination));
    }
}
JavaScript
// JavaScript Code to find count of paths between 
// two vertices of a directed graph using DFS 
function dfs(node, dest, graph, visited, count) {

    // If destination is reached, 
    // increment count
    if (node === dest) {
        count.value++;
        return;
    }

    // Mark current node as visited
    visited[node] = true;

    // Explore all unvisited neighbors
    for (let neighbor of graph[node]) {
        if (!visited[neighbor]) {
            dfs(neighbor, dest, graph, visited, count);
        }
    }

    // Backtrack: unmark the node 
    // before returning
    visited[node] = false;
}

function countPaths(n, edgeList, source, destination) {

    // Create adjacency list(1 - based indexing)
    let graph = Array.from({ length: n + 1 }, () => []);
    for (let [u, v] of edgeList) {
        graph[u].push(v);
    }

    // Track visited nodes
    let visited = Array(n + 1).fill(false);
    let count = { value: 0 };

    // Start DFS from source
    dfs(source, destination, graph, visited, count);

    return count.value;
}

// Driver Code
let n = 5;

// Edge list: [u, v] represents u -> v
let edgeList = [
    [1, 2], [1, 3], [1, 5],
    [2, 5], [2, 4], [3, 5], [4, 3]
];

let source = 1;
let destination = 5;

console.log(countPaths(n, edgeList, source, destination));

Output
4

Time Complexity: O(2^n), In the worst case, every node branches to all others, exploring all simple paths.
Space Complexity: O(n), Stack space for recursion and visited array proportional to number of nodes.

[Approach - 2] Using Topological Sort - O(n) Time and O(n) Space

The idea is to count all paths from a source to destination in a directed graph using topological sorting. The thought process is that by processing nodes in topological order, we ensure we always compute paths after all its predecessors are processed. We maintain a ways[] array where ways[i] stores the number of paths to reach node i from the source. An important observation is that once we know the number of ways to reach a node, we can propagate that to its outgoing neighbors.

Steps to implement the above idea:

  • Construct the adjacency list from the given edge list using 1-based indexing for all graph nodes.
  • Initialize an indegree array to count incoming edges for each node for topological sorting.
  • Use queue to generate the topological order of the graph.
  • Create a ways array to store the number of distinct paths to each node from the source.
  • Set the path count of the source node to 1 as a base for path propagation.
  • Traverse all nodes in topological order and for each node update its neighbors' path counts.
  • Return the value at the destination node from the ways array as the total number of paths.
C++
// C++ Code to count paths from source 
// to destinattion using Topological Sort
#include <bits/stdc++.h>
using namespace std;

int countPaths(int n, vector<vector<int>> &edgeList,
               int source, int destination) {

    // Create adjacency list (1-based indexing)
    vector<vector<int>> graph(n + 1);
    vector<int> indegree(n + 1, 0);

    for (auto &edge : edgeList) {
        int u = edge[0];
        int v = edge[1];
        graph[u].push_back(v);
        indegree[v]++;
    }

    // Perform topological sort using Kahn's algorithm
    queue<int> q;
    for (int i = 1; i <= n; i++) {
        if (indegree[i] == 0) {
            q.push(i);
        }
    }

    vector<int> topoOrder;
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        topoOrder.push_back(node);

        for (int neighbor : graph[node]) {
            indegree[neighbor]--;
            if (indegree[neighbor] == 0) {
                q.push(neighbor);
            }
        }
    }

    // Array to store number of ways to reach each node
    vector<int> ways(n + 1, 0);
    ways[source] = 1;

    // Traverse in topological order
    for (int node : topoOrder) {
        for (int neighbor : graph[node]) {
            ways[neighbor] += ways[node];
        }
    }

    return ways[destination];
}

int main() {

    int n = 5;

    // Edge list: [u, v] represents u -> v
    vector<vector<int>> edgeList = {
        {1, 2}, {1, 3}, {1, 5},
        {2, 5}, {2, 4}, {3, 5}, {4, 3}
    };

    int source = 1;
    int destination = 5;

    cout << countPaths(n, edgeList, source, destination);

    return 0;
}
Java
// Java Code to count paths from source 
// to destinattion using Topological Sort
import java.util.*;

class GfG {

    static int countPaths(int n, int[][] edgeList,
                          int source, int destination) {

        // Create adjacency list (1-based indexing)
        List<Integer>[] graph = new ArrayList[n + 1];
        int[] indegree = new int[n + 1];

        for (int i = 0; i <= n; i++) {
            graph[i] = new ArrayList<>();
        }

        for (int[] edge : edgeList) {
            int u = edge[0];
            int v = edge[1];
            graph[u].add(v);
            indegree[v]++;
        }

        // Perform topological sort using Kahn's algorithm
        Queue<Integer> q = new LinkedList<>();
        for (int i = 1; i <= n; i++) {
            if (indegree[i] == 0) {
                q.add(i);
            }
        }

        List<Integer> topoOrder = new ArrayList<>();
        while (!q.isEmpty()) {
            int node = q.poll();
            topoOrder.add(node);

            for (int neighbor : graph[node]) {
                indegree[neighbor]--;
                if (indegree[neighbor] == 0) {
                    q.add(neighbor);
                }
            }
        }

        // Array to store number of ways to reach each node
        int[] ways = new int[n + 1];
        ways[source] = 1;

        // Traverse in topological order
        for (int node : topoOrder) {
            for (int neighbor : graph[node]) {
                ways[neighbor] += ways[node];
            }
        }

        return ways[destination];
    }

    public static void main(String[] args) {

        int n = 5;

        // Edge list: [u, v] represents u -> v
        int[][] edgeList = {
            {1, 2}, {1, 3}, {1, 5},
            {2, 5}, {2, 4}, {3, 5}, {4, 3}
        };

        int source = 1;
        int destination = 5;

        System.out.println(countPaths(n, edgeList, source, destination));
    }
}
Python
# Python Code to count paths from source 
# to destinattion using Topological Sort
from collections import deque

def countPaths(n, edgeList, source, destination):

    # Create adjacency list (1-based indexing)
    graph = [[] for _ in range(n + 1)]
    indegree = [0] * (n + 1)

    for u, v in edgeList:
        graph[u].append(v)
        indegree[v] += 1

    # Perform topological sort using Kahn's algorithm
    q = deque()
    for i in range(1, n + 1):
        if indegree[i] == 0:
            q.append(i)

    topoOrder = []
    while q:
        node = q.popleft()
        topoOrder.append(node)

        for neighbor in graph[node]:
            indegree[neighbor] -= 1
            if indegree[neighbor] == 0:
                q.append(neighbor)

    # Array to store number of ways to reach each node
    ways = [0] * (n + 1)
    ways[source] = 1

    # Traverse in topological order
    for node in topoOrder:
        for neighbor in graph[node]:
            ways[neighbor] += ways[node]

    return ways[destination]

if __name__ == "__main__":

    n = 5

    # Edge list: [u, v] represents u -> v
    edgeList = [
        [1, 2], [1, 3], [1, 5],
        [2, 5], [2, 4], [3, 5], [4, 3]
    ]

    source = 1
    destination = 5

    print(countPaths(n, edgeList, source, destination))
C#
// C# Code to count paths from source 
// to destinattion using Topological Sort
using System;
using System.Collections.Generic;

class GfG {

    static int countPaths(int n, int[][] edgeList,
                          int source, int destination) {

        // Create adjacency list (1-based indexing)
        List<int>[] graph = new List<int>[n + 1];
        int[] indegree = new int[n + 1];

        for (int i = 0; i <= n; i++) {
            graph[i] = new List<int>();
        }

        foreach (var edge in edgeList) {
            int u = edge[0];
            int v = edge[1];
            graph[u].Add(v);
            indegree[v]++;
        }

        // Perform topological sort using Kahn's algorithm
        Queue<int> q = new Queue<int>();
        for (int i = 1; i <= n; i++) {
            if (indegree[i] == 0) {
                q.Enqueue(i);
            }
        }

        List<int> topoOrder = new List<int>();
        while (q.Count > 0) {
            int node = q.Dequeue();
            topoOrder.Add(node);

            foreach (int neighbor in graph[node]) {
                indegree[neighbor]--;
                if (indegree[neighbor] == 0) {
                    q.Enqueue(neighbor);
                }
            }
        }

        // Array to store number of ways to reach each node
        int[] ways = new int[n + 1];
        ways[source] = 1;

        // Traverse in topological order
        foreach (int node in topoOrder) {
            foreach (int neighbor in graph[node]) {
                ways[neighbor] += ways[node];
            }
        }

        return ways[destination];
    }

    static void Main() {

        int n = 5;

        // Edge list: [u, v] represents u -> v
        int[][] edgeList = {
            new int[]{1, 2}, new int[]{1, 3}, new int[]{1, 5},
            new int[]{2, 5}, new int[]{2, 4}, new int[]{3, 5}, new int[]{4, 3}
        };

        int source = 1;
        int destination = 5;

        Console.WriteLine(countPaths(n, edgeList, source, destination));
    }
}
JavaScript
// JavaScript Code to count paths from source 
// to destinattion using Topological Sort

function countPaths(n, edgeList, source, destination) {

    // Create adjacency list (1-based indexing)
    let graph = Array.from({ length: n + 1 }, () => []);
    let indegree = Array(n + 1).fill(0);

    for (let [u, v] of edgeList) {
        graph[u].push(v);
        indegree[v]++;
    }

    // Perform topological sort using Kahn's algorithm
    let q = [];
    for (let i = 1; i <= n; i++) {
        if (indegree[i] === 0) {
            q.push(i);
        }
    }

    let topoOrder = [];
    while (q.length > 0) {
        let node = q.shift();
        topoOrder.push(node);

        for (let neighbor of graph[node]) {
            indegree[neighbor]--;
            if (indegree[neighbor] === 0) {
                q.push(neighbor);
            }
        }
    }

    // Array to store number of ways to reach each node
    let ways = Array(n + 1).fill(0);
    ways[source] = 1;

    // Traverse in topological order
    for (let node of topoOrder) {
        for (let neighbor of graph[node]) {
            ways[neighbor] += ways[node];
        }
    }

    return ways[destination];
}

// Driver Code
let n = 5;

// Edge list: [u, v] represents u -> v
let edgeList = [
    [1, 2], [1, 3], [1, 5],
    [2, 5], [2, 4], [3, 5], [4, 3]
];

let source = 1;
let destination = 5;

console.log(countPaths(n, edgeList, source, destination));

Output
4

Time Complexity: O(n + e), Each node and edge is processed once for topological sort and path update, where e is the total number of edges.
Space Complexity: O(n + e), Extra space is used for the adjacency list, indegree array, and ways array.



Next Article
Article Tags :
Practice Tags :

Similar Reads