VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-paths-given-source-destination/

⇱ Print all paths from a given source to a destination - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print all paths from a given source to a destination

Last Updated : 23 Jul, 2025

Given a directed acyclic graph, a source vertex src and a destination vertex dest, print all paths from given src to dest

Examples:

Input: V = 4, edges[ ][ ] = [[0, 1], [1, 2], [1, 3], [2, 3]], src = 0, dest = 3
Output: [[0, 1, 2, 3], [0, 1, 3]]
Explanation: There are two ways to reach at 3 from 0. These are: 0 -> 1 -> 3 and 0 -> 1 -> 2 -> 3.

👁 Print-all-paths-2

Input: V = 4, edges[ ][ ] = [[0, 3], [0, 1], [1, 3], [2, 1], [2, 0]], src = 2, dest = 3
Output: [[2, 1, 3], [2, 0, 3], [2, 0, 1, 3]]
Explanation: There are three ways to reach at 3 from 2. These are: 2 -> 1 -> 3, 2 -> 0 -> 3 and 2 -> 0 -> 1 -> 3.

👁 Print-all-paths-1

[Approach 1] Using DFS

The main idea uses DFS to explore all paths from the source to the destination in a directed graph. It recursively builds paths, stores them when the destination is reached, and backtracks to explore alternative routes.


Output
2 0 3 
2 0 1 3 
2 1 3 

Time Complexity: O(2V ), where V is number of vertices. There can be at most 2V paths in the graph
Auxiliary Space: O(V + E)

[Approach 2] Using BFS

The main idea is to use Breadth-First Search (BFS) to find all paths from a source to a destination in a directed graph. It uses a queue to explore all possible paths level by level. Each path is stored and extended by adding adjacent nodes, and when the destination is reached, the current path is added to the result.


Output
2 0 3 
2 1 3 
2 0 1 3 

Time Complexity: O(2V), where V is number of vertices. There can be at most 2V paths in the graph
Auxiliary Space: O(V + E)

Comment
Article Tags: