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.
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.
[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.
C++
// C++ Program to print all paths
// from source to destination
#include <iostream>
#include <vector>
using namespace std;
void dfs(int src, int dest, vector<vector<int>> &graph, vector<int> &path,
vector<vector<int>> &allPaths){
// Add the current vertex to the path
path.push_back(src);
// Store the path when destination is reached
if (src == dest){
allPaths.push_back(path);
}
else{
for (int adj_node:graph[src]){
dfs(adj_node, dest, graph, path, allPaths);
}
}
// remove the current vertex from the path
path.pop_back();
}
vector<vector<int>> findPaths(int v, vector<vector<int>> &edges, int src, int dest){
vector<vector<int>> graph(v);
// Build the graph from edges
for (const auto &edge : edges){
graph[edge[0]].push_back(edge[1]);
}
vector<vector<int>> allPaths;
vector<int> path;
dfs(src, dest, graph, path, allPaths);
return allPaths;
}
int main(){
vector<vector<int>> edges = {{0, 3}, {0, 1}, {1, 3}, {2, 0}, {2, 1}};
int src = 2, dest = 3;
int v = 4;
vector<vector<int>> paths = findPaths(v, edges, src, dest);
for (const auto &path : paths){
for (int vtx : path){
cout << vtx << " ";
}
cout << endl;
}
return 0;
}
Java
// Java Program to print all paths
// from source to destination
import java.util.ArrayList;
import java.util.List;
class GfG {
static ArrayList<ArrayList<Integer>> dfs(int src, int dest,
List<List<Integer>> graph, ArrayList<Integer> path,
ArrayList<ArrayList<Integer>> allPaths) {
// Add the current vertex to the path
path.add(src);
// Store the path when destination is reached
if (src == dest) {
allPaths.add(new ArrayList<>(path));
} else {
for (int adjNode : graph.get(src)) {
dfs(adjNode, dest, graph, path, allPaths);
}
}
// remove the current vertex from the path
path.remove(path.size() - 1);
return allPaths;
}
static ArrayList<ArrayList<Integer>> findPaths(int v, int[][] edges,
int src, int dest) {
List<List<Integer>> graph = new ArrayList<>();
// Build the graph from edges
for (int i = 0; i < v; i++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
}
ArrayList<ArrayList<Integer>> allPaths = new ArrayList<>();
ArrayList<Integer> path = new ArrayList<>();
dfs(src, dest, graph, path, allPaths);
return allPaths;
}
public static void main(String[] args) {
int[][] edges = {{0, 3}, {0, 1}, {1, 3}, {2, 0}, {2, 1}};
int src = 2, dest = 3;
int v = 4;
ArrayList<ArrayList<Integer>> paths = findPaths(v, edges, src, dest);
for (ArrayList<Integer> path : paths) {
for (int vtx : path) {
System.out.print(vtx + " ");
}
System.out.println();
}
}
}
Python
# Python Program to print all paths
# from source to destination
def dfs(src, dest, graph, path, allPaths):
# Add the current vertex to the path
path.append(src)
# Store the path when destination is reached
if src == dest:
allPaths.append(path.copy())
else:
for adj_node in graph[src]:
dfs(adj_node, dest, graph, path, allPaths)
# remove the current vertex from the path
path.pop()
def findPaths(v, edges, src, dest):
graph = [[] for _ in range(v)]
# Build the graph from edges
for edge in edges:
graph[edge[0]].append(edge[1])
allPaths = []
path = []
dfs(src, dest, graph, path, allPaths)
return allPaths
if __name__ == "__main__":
edges = [[0, 3], [0, 1], [1, 3], [2, 0], [2, 1]]
src = 2
dest = 3
v = 4
paths = findPaths(v, edges, src, dest)
for path in paths:
for vtx in path:
print(vtx, end=" ")
print()
C#
using System;
using System.Collections.Generic;
class GfG {
static void dfs(int src, int dest, int[,] graph, bool[] visited,
List<int> path,
List<List<int>> allPaths) {
// Add the current vertex to the path
path.Add(src);
// If destination is reached, store the path
if (src == dest) {
allPaths.Add(new List<int>(path));
}
else {
// Recurse for all adjacent vertices
for (int adjNode = 0; adjNode < graph.GetLength(0); adjNode++) {
if (graph[src, adjNode] == 1 && !visited[adjNode]) {
visited[adjNode] = true;
dfs(adjNode, dest, graph, visited, path, allPaths);
visited[adjNode] = false;
}
}
}
// Remove the current vertex from path
path.RemoveAt(path.Count - 1);
}
public static List<List<int>> FindPaths(int v, int[,] edges, int src, int dest) {
int[,] graph = new int[v, v];
// Build the graph from edges
for (int i = 0; i < edges.GetLength(0); i++) {
int u = edges[i, 0];
int vtx = edges[i, 1];
// mark the edge between u and vtx
graph[u, vtx] = 1;
}
bool[] visited = new bool[v];
List<int> path = new List<int>();
List<List<int>> allPaths = new List<List<int>>();
visited[src] = true;
dfs(src, dest, graph, visited, path, allPaths);
return allPaths;
}
public static void Main(string[] args) {
int[,] edges = new int[,]
{
{ 0, 3 }, { 0, 1 }, { 1, 3 }, { 2, 0 }, { 2, 1 }
};
int src = 2, dest = 3;
int v = 4;
List<List<int>> paths = FindPaths(v, edges, src, dest);
foreach (List<int> path in paths) {
foreach (int vtx in path) {
Console.Write(vtx + " ");
}
Console.WriteLine();
}
}
}
JavaScript
// JavaScript Program to print all paths
// from source to destination
function dfs(src, dest, graph, path, allPaths){
// Add the current vertex to the path
path.push(src);
// Store the path when destination is reached
if (src === dest) {
allPaths.push([...path ]);
}
else {
for (let adjNode of graph[src]) {
dfs(adjNode, dest, graph, path, allPaths);
}
}
// remove the current vertex from the path
path.pop();
}
function findPaths(v, edges, src, dest){
let graph = Array.from({length : v}, () => []);
// Build the graph from edges
for (let edge of edges) {
graph[edge[0]].push(edge[1]);
}
let allPaths = [];
let path = [];
dfs(src, dest, graph, path, allPaths);
return allPaths;
}
// Driver Code
const edges =
[ [ 0, 3 ], [ 0, 1 ], [ 1, 3 ], [ 2, 0 ], [ 2, 1 ] ];
const src = 2;
const dest = 3;
const v = 4;
const paths = findPaths(v, edges, src, dest);
for (const path of paths) {
console.log(path.join(" "));
}
Output2 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.
C++
// C++ Program to find all paths
// from source to destination in a directed graph
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
vector<vector<int>> findPaths(int v, vector<vector<int>> &edges,
int src, int dest) {
vector<vector<int>> graph(v);
// Build the graph from edges
for (const auto &edge : edges) {
graph[edge[0]].push_back(edge[1]);
}
vector<vector<int>> allPaths;
queue<vector<int>> q;
// Initialize queue with the starting path
q.push({src});
while (!q.empty()) {
vector<int> path = q.front();
q.pop();
int current = path.back();
// If destination is reached, store the path
if (current == dest) {
allPaths.push_back(path);
}
// Explore all adjacent vertices
for (int adj : graph[current]) {
vector<int> newPath = path;
newPath.push_back(adj);
q.push(newPath);
}
}
return allPaths;
}
int main() {
vector<vector<int>> edges = {{0, 3}, {0, 1}, {1, 3}, {2, 0}, {2, 1}};
int src = 2, dest = 3;
int v = 4;
// Find all paths from source to destination
vector<vector<int>> paths = findPaths(v, edges, src, dest);
// Print all the paths
for (const auto &path : paths) {
for (int vtx : path) {
cout << vtx << " ";
}
cout << endl;
}
return 0;
}
Java
// Java Program to find all paths
// from source to destination in a directed graph
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class GfG {
public static ArrayList<ArrayList<Integer>> findPaths(int v, int[][] edges, int src, int dest) {
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for (int i = 0; i < v; i++) {
graph.add(new ArrayList<>());
}
// Build the graph from edges
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
}
ArrayList<ArrayList<Integer>> allPaths = new ArrayList<>();
Queue<ArrayList<Integer>> q = new LinkedList<>();
// Initialize queue with the starting path
ArrayList<Integer> initialPath = new ArrayList<>();
initialPath.add(src);
q.add(initialPath);
while (!q.isEmpty()) {
ArrayList<Integer> path = q.poll();
int current = path.get(path.size() - 1);
// If destination is reached, store the path
if (current == dest) {
allPaths.add(new ArrayList<>(path));
}
// Explore all adjacent vertices
for (int adj : graph.get(current)) {
ArrayList<Integer> newPath = new ArrayList<>(path);
newPath.add(adj);
q.add(newPath);
}
}
return allPaths;
}
public static void main(String[] args) {
int[][] edges = {{0, 3}, {0, 1}, {1, 3}, {2, 0}, {2, 1}};
int src = 2, dest = 3;
int v = 4;
// Find all paths from source to destination
ArrayList<ArrayList<Integer>> paths = findPaths(v, edges, src, dest);
// Print all the paths
for (ArrayList<Integer> path : paths) {
for (int vtx : path) {
System.out.print(vtx + " ");
}
System.out.println();
}
}
}
Python
# Python Program to find all paths
# from source to destination in a directed graph
from collections import deque
def findPaths(v, edges, src, dest):
graph = [[] for _ in range(v)]
# Build the graph from edges
for edge in edges:
graph[edge[0]].append(edge[1])
allPaths = []
q = deque()
# Initialize queue with the starting path
q.append([src])
while q:
path = q.popleft()
current = path[-1]
# If destination is reached, store the path
if current == dest:
allPaths.append(path)
# Explore all adjacent vertices
for adj in graph[current]:
newPath = list(path)
newPath.append(adj)
q.append(newPath)
return allPaths
if __name__ == "__main__":
edges = [[0, 3], [0, 1], [1, 3], [2, 0], [2, 1]]
src = 2
dest = 3
v = 4
# Find all paths from source to destination
paths = findPaths(v, edges, src, dest)
# Print all the paths
for path in paths:
for vtx in path:
print(vtx, end=" ")
print()
C#
// C# Program to find all paths
// from source to destination in a directed graph
using System;
using System.Collections.Generic;
class GfG {
public static List<List<int>>
findPaths(int v, int[, ] edges, int src, int dest) {
List<List<int> > graph = new List<List<int> >();
for (int i = 0; i < v; i++) {
graph.Add(new List<int>());
}
// Build the graph from edges
int edgeCount = edges.GetLength(0);
for (int i = 0; i < edgeCount; i++) {
int u = edges[i, 0];
int vtx = edges[i, 1];
graph[u].Add(vtx);
}
List<List<int> > allPaths = new List<List<int> >();
Queue<List<int> > q = new Queue<List<int> >();
// Initialize queue with the starting path
q.Enqueue(new List<int>{ src });
while (q.Count > 0) {
List<int> path = q.Dequeue();
int current = path[path.Count - 1];
// If destination is reached, store the path
if (current == dest) {
allPaths.Add(new List<int>(path));
}
// Explore all adjacent vertices
foreach(int adj in graph[current]) {
List<int> newPath = new List<int>(path);
newPath.Add(adj);
q.Enqueue(newPath);
}
}
return allPaths;
}
static void Main(){
int[, ] edges = {
{ 0, 3 }, { 0, 1 }, { 1, 3 }, { 2, 0 }, { 2, 1 }
};
int src = 2, dest = 3;
int v = 4;
// Find all paths from source to destination
var paths = findPaths(v, edges, src, dest);
// Print all the paths
foreach(var path in paths) {
Console.WriteLine(string.Join(" ", path));
}
}
}
JavaScript
// JavaScript Program to find all paths
// from source to destination in a directed graph
function findPaths(v, edges, src, dest) {
const graph = Array.from({ length: v }, () => []);
// Build the graph from edges
for (const edge of edges) {
graph[edge[0]].push(edge[1]);
}
const allPaths = [];
const q = [];
// Initialize queue with the starting path
q.push([src]);
while (q.length > 0) {
const path = q.shift();
const current = path[path.length - 1];
// If destination is reached, store the path
if (current === dest) {
allPaths.push(path);
}
// Explore all adjacent vertices
for (const adj of graph[current]) {
const newPath = [...path, adj];
q.push(newPath);
}
}
return allPaths;
}
// Driver Code
const edges = [[0, 3], [0, 1], [1, 3], [2, 0], [2, 1]];
const src = 2, dest = 3;
const v = 4;
// Find all paths from source to destination
const paths = findPaths(v, edges, src, dest);
// Print all the paths
for (const path of paths) {
console.log(path.join(' '));
}
Output2 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)
Count the paths | DSA Problem
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem