VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-possible-paths-two-vertices/

⇱ Count all possible Paths between two Vertices - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:

👁 ss


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. 

👁 Image


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

👁 Image


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.

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.

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.


Comment