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>usingnamespacestd;voiddfs(intsrc,intdest,vector<vector<int>>&graph,vector<int>&path,vector<vector<int>>&allPaths){// Add the current vertex to the pathpath.push_back(src);// Store the path when destination is reachedif(src==dest){allPaths.push_back(path);}else{for(intadj_node:graph[src]){dfs(adj_node,dest,graph,path,allPaths);}}// remove the current vertex from the pathpath.pop_back();}vector<vector<int>>findPaths(intv,vector<vector<int>>&edges,intsrc,intdest){vector<vector<int>>graph(v);// Build the graph from edgesfor(constauto&edge:edges){graph[edge[0]].push_back(edge[1]);}vector<vector<int>>allPaths;vector<int>path;dfs(src,dest,graph,path,allPaths);returnallPaths;}intmain(){vector<vector<int>>edges={{0,3},{0,1},{1,3},{2,0},{2,1}};intsrc=2,dest=3;intv=4;vector<vector<int>>paths=findPaths(v,edges,src,dest);for(constauto&path:paths){for(intvtx:path){cout<<vtx<<" ";}cout<<endl;}return0;}
Java
// Java Program to print all paths// from source to destination importjava.util.ArrayList;importjava.util.List;classGfG{staticArrayList<ArrayList<Integer>>dfs(intsrc,intdest,List<List<Integer>>graph,ArrayList<Integer>path,ArrayList<ArrayList<Integer>>allPaths){// Add the current vertex to the pathpath.add(src);// Store the path when destination is reachedif(src==dest){allPaths.add(newArrayList<>(path));}else{for(intadjNode:graph.get(src)){dfs(adjNode,dest,graph,path,allPaths);}}// remove the current vertex from the pathpath.remove(path.size()-1);returnallPaths;}staticArrayList<ArrayList<Integer>>findPaths(intv,int[][]edges,intsrc,intdest){List<List<Integer>>graph=newArrayList<>();// Build the graph from edgesfor(inti=0;i<v;i++){graph.add(newArrayList<>());}for(int[]edge:edges){graph.get(edge[0]).add(edge[1]);}ArrayList<ArrayList<Integer>>allPaths=newArrayList<>();ArrayList<Integer>path=newArrayList<>();dfs(src,dest,graph,path,allPaths);returnallPaths;}publicstaticvoidmain(String[]args){int[][]edges={{0,3},{0,1},{1,3},{2,0},{2,1}};intsrc=2,dest=3;intv=4;ArrayList<ArrayList<Integer>>paths=findPaths(v,edges,src,dest);for(ArrayList<Integer>path:paths){for(intvtx:path){System.out.print(vtx+" ");}System.out.println();}}}
Python
# Python Program to print all paths# from source to destination defdfs(src,dest,graph,path,allPaths):# Add the current vertex to the pathpath.append(src)# Store the path when destination is reachedifsrc==dest:allPaths.append(path.copy())else:foradj_nodeingraph[src]:dfs(adj_node,dest,graph,path,allPaths)# remove the current vertex from the pathpath.pop()deffindPaths(v,edges,src,dest):graph=[[]for_inrange(v)]# Build the graph from edgesforedgeinedges:graph[edge[0]].append(edge[1])allPaths=[]path=[]dfs(src,dest,graph,path,allPaths)returnallPathsif__name__=="__main__":edges=[[0,3],[0,1],[1,3],[2,0],[2,1]]src=2dest=3v=4paths=findPaths(v,edges,src,dest)forpathinpaths:forvtxinpath:print(vtx,end=" ")print()
C#
usingSystem;usingSystem.Collections.Generic;classGfG{staticvoiddfs(intsrc,intdest,int[,]graph,bool[]visited,List<int>path,List<List<int>>allPaths){// Add the current vertex to the pathpath.Add(src);// If destination is reached, store the pathif(src==dest){allPaths.Add(newList<int>(path));}else{// Recurse for all adjacent verticesfor(intadjNode=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 pathpath.RemoveAt(path.Count-1);}publicstaticList<List<int>>FindPaths(intv,int[,]edges,intsrc,intdest){int[,]graph=newint[v,v];// Build the graph from edgesfor(inti=0;i<edges.GetLength(0);i++){intu=edges[i,0];intvtx=edges[i,1];// mark the edge between u and vtxgraph[u,vtx]=1;}bool[]visited=newbool[v];List<int>path=newList<int>();List<List<int>>allPaths=newList<List<int>>();visited[src]=true;dfs(src,dest,graph,visited,path,allPaths);returnallPaths;}publicstaticvoidMain(string[]args){int[,]edges=newint[,]{{0,3},{0,1},{1,3},{2,0},{2,1}};intsrc=2,dest=3;intv=4;List<List<int>>paths=FindPaths(v,edges,src,dest);foreach(List<int>pathinpaths){foreach(intvtxinpath){Console.Write(vtx+" ");}Console.WriteLine();}}}
JavaScript
// JavaScript Program to print all paths// from source to destinationfunctiondfs(src,dest,graph,path,allPaths){// Add the current vertex to the pathpath.push(src);// Store the path when destination is reachedif(src===dest){allPaths.push([...path]);}else{for(letadjNodeofgraph[src]){dfs(adjNode,dest,graph,path,allPaths);}}// remove the current vertex from the pathpath.pop();}functionfindPaths(v,edges,src,dest){letgraph=Array.from({length:v},()=>[]);// Build the graph from edgesfor(letedgeofedges){graph[edge[0]].push(edge[1]);}letallPaths=[];letpath=[];dfs(src,dest,graph,path,allPaths);returnallPaths;}// Driver Codeconstedges=[[0,3],[0,1],[1,3],[2,0],[2,1]];constsrc=2;constdest=3;constv=4;constpaths=findPaths(v,edges,src,dest);for(constpathofpaths){console.log(path.join(" "));}
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.
C++
// C++ Program to find all paths // from source to destination in a directed graph#include<iostream>#include<queue>#include<vector>usingnamespacestd;vector<vector<int>>findPaths(intv,vector<vector<int>>&edges,intsrc,intdest){vector<vector<int>>graph(v);// Build the graph from edgesfor(constauto&edge:edges){graph[edge[0]].push_back(edge[1]);}vector<vector<int>>allPaths;queue<vector<int>>q;// Initialize queue with the starting pathq.push({src});while(!q.empty()){vector<int>path=q.front();q.pop();intcurrent=path.back();// If destination is reached, store the pathif(current==dest){allPaths.push_back(path);}// Explore all adjacent verticesfor(intadj:graph[current]){vector<int>newPath=path;newPath.push_back(adj);q.push(newPath);}}returnallPaths;}intmain(){vector<vector<int>>edges={{0,3},{0,1},{1,3},{2,0},{2,1}};intsrc=2,dest=3;intv=4;// Find all paths from source to destinationvector<vector<int>>paths=findPaths(v,edges,src,dest);// Print all the pathsfor(constauto&path:paths){for(intvtx:path){cout<<vtx<<" ";}cout<<endl;}return0;}
Java
// Java Program to find all paths // from source to destination in a directed graphimportjava.util.ArrayList;importjava.util.LinkedList;importjava.util.Queue;publicclassGfG{publicstaticArrayList<ArrayList<Integer>>findPaths(intv,int[][]edges,intsrc,intdest){ArrayList<ArrayList<Integer>>graph=newArrayList<>();for(inti=0;i<v;i++){graph.add(newArrayList<>());}// Build the graph from edgesfor(int[]edge:edges){graph.get(edge[0]).add(edge[1]);}ArrayList<ArrayList<Integer>>allPaths=newArrayList<>();Queue<ArrayList<Integer>>q=newLinkedList<>();// Initialize queue with the starting pathArrayList<Integer>initialPath=newArrayList<>();initialPath.add(src);q.add(initialPath);while(!q.isEmpty()){ArrayList<Integer>path=q.poll();intcurrent=path.get(path.size()-1);// If destination is reached, store the pathif(current==dest){allPaths.add(newArrayList<>(path));}// Explore all adjacent verticesfor(intadj:graph.get(current)){ArrayList<Integer>newPath=newArrayList<>(path);newPath.add(adj);q.add(newPath);}}returnallPaths;}publicstaticvoidmain(String[]args){int[][]edges={{0,3},{0,1},{1,3},{2,0},{2,1}};intsrc=2,dest=3;intv=4;// Find all paths from source to destinationArrayList<ArrayList<Integer>>paths=findPaths(v,edges,src,dest);// Print all the pathsfor(ArrayList<Integer>path:paths){for(intvtx:path){System.out.print(vtx+" ");}System.out.println();}}}
Python
# Python Program to find all paths # from source to destination in a directed graphfromcollectionsimportdequedeffindPaths(v,edges,src,dest):graph=[[]for_inrange(v)]# Build the graph from edgesforedgeinedges:graph[edge[0]].append(edge[1])allPaths=[]q=deque()# Initialize queue with the starting pathq.append([src])whileq:path=q.popleft()current=path[-1]# If destination is reached, store the pathifcurrent==dest:allPaths.append(path)# Explore all adjacent verticesforadjingraph[current]:newPath=list(path)newPath.append(adj)q.append(newPath)returnallPathsif__name__=="__main__":edges=[[0,3],[0,1],[1,3],[2,0],[2,1]]src=2dest=3v=4# Find all paths from source to destinationpaths=findPaths(v,edges,src,dest)# Print all the pathsforpathinpaths:forvtxinpath:print(vtx,end=" ")print()
C#
// C# Program to find all paths// from source to destination in a directed graphusingSystem;usingSystem.Collections.Generic;classGfG{publicstaticList<List<int>>findPaths(intv,int[,]edges,intsrc,intdest){List<List<int>>graph=newList<List<int>>();for(inti=0;i<v;i++){graph.Add(newList<int>());}// Build the graph from edgesintedgeCount=edges.GetLength(0);for(inti=0;i<edgeCount;i++){intu=edges[i,0];intvtx=edges[i,1];graph[u].Add(vtx);}List<List<int>>allPaths=newList<List<int>>();Queue<List<int>>q=newQueue<List<int>>();// Initialize queue with the starting pathq.Enqueue(newList<int>{src});while(q.Count>0){List<int>path=q.Dequeue();intcurrent=path[path.Count-1];// If destination is reached, store the pathif(current==dest){allPaths.Add(newList<int>(path));}// Explore all adjacent verticesforeach(intadjingraph[current]){List<int>newPath=newList<int>(path);newPath.Add(adj);q.Enqueue(newPath);}}returnallPaths;}staticvoidMain(){int[,]edges={{0,3},{0,1},{1,3},{2,0},{2,1}};intsrc=2,dest=3;intv=4;// Find all paths from source to destinationvarpaths=findPaths(v,edges,src,dest);// Print all the pathsforeach(varpathinpaths){Console.WriteLine(string.Join(" ",path));}}}
JavaScript
// JavaScript Program to find all paths // from source to destination in a directed graphfunctionfindPaths(v,edges,src,dest){constgraph=Array.from({length:v},()=>[]);// Build the graph from edgesfor(constedgeofedges){graph[edge[0]].push(edge[1]);}constallPaths=[];constq=[];// Initialize queue with the starting pathq.push([src]);while(q.length>0){constpath=q.shift();constcurrent=path[path.length-1];// If destination is reached, store the pathif(current===dest){allPaths.push(path);}// Explore all adjacent verticesfor(constadjofgraph[current]){constnewPath=[...path,adj];q.push(newPath);}}returnallPaths;}// Driver Codeconstedges=[[0,3],[0,1],[1,3],[2,0],[2,1]];constsrc=2,dest=3;constv=4;// Find all paths from source to destinationconstpaths=findPaths(v,edges,src,dest);// Print all the pathsfor(constpathofpaths){console.log(path.join(' '));}
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)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.