Given a directed graph, a source vertex ‘s’ and a destination vertex ‘d’, print all paths from given ‘s’ to ‘d’.
Consider the following directed graph. Let the s be 2 and d be 3. There are 4 different paths from 2 to 3.
- The idea is to do Depth First Traversal of given directed graph.
- Start the DFS traversal from source.
- Keep storing the visited vertices in an array or HashMap say ‘path’.
- If the destination vertex is reached, print contents of path.
- The important thing is to mark current vertices in the path as visited also so that the traversal doesn’t go in a cycle.
Following is implementation of above idea.
Following are all different paths from 2 to 3 2 0 1 3 2 0 3 2 1 3
- Time Complexity: O(V^V).
The time complexity is polynomial. From each vertex there are v vertices that can be visited from current vertex.
- Auxiliary space: O(V^V).
To store the paths V^V space is needed.
This article is contributed by Shivam Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print all paths from a given source to a destination using BFS
- Print all shortest paths between given source and destination in an undirected graph
- Print path from given Source to Destination in 2-D Plane
- Count all possible walks from a source to a destination with exactly k edges
- Shortest paths from all vertices to a destination
- Minimum edges to reverse to make path from a source to a destination
- Minimum cost path from source node to destination node via an intermediate node
- Number of Walks from source to destination
- Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
- Sum of shortest distance on source to destination and back having at least a common vertex
- Shortest path in a graph from a source S to destination D with exactly K edges for multiple Queries
- Count total ways to reach destination from source in an undirected Graph
- Shortest Path with even number of Edges from Source to Destination
- Print all possible paths from top left to bottom right of a mXn matrix
- Print all possible paths from the first row to the last row in a 2D array
- Print all paths of the Binary Tree with maximum element in each path greater than or equal to K
- Print all possible paths in a DAG from vertex whose indegree is 0
- Count number of times each Edge appears in all possible paths of a given Tree
- Find the minimum cost to reach destination using a train
- Number of decisions to reach destination