Count all possible Paths between two Vertices
Last Updated :
24 Jul, 2025
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:

Input: n = 5, edgeList[][] = [[A, B], [A, C], [A, E], [B, E], [B, D], [C, E], [D, C]], source = A, destination = E
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));
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));
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem