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 traversal from source. Keep storing the visited vertices in an array say ‘path’. If we reach the destination vertex, print contents of path. The important thing is to mark current vertices in 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
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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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
- Number of Walks from source to destination
- Count all possible walks from a source to a destination with exactly k edges
- Shortest Path with even number of Edges from Source to Destination
- Minimum edges to reverse to make path from a source to a destination
- Shortest paths from all vertices to a destination
- Count total ways to reach destination from source in an undirected Graph
- Shortest path in a graph from a source S to destination D with exactly K edges for multiple Queries
- Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
- Minimum cost path from source node to destination node via an intermediate node
- Print all possible paths from the first row to the last row in a 2D array
- Print all possible paths from top left to bottom right of a mXn matrix
- Print Palindromic Paths of Binary tree
- Print all paths of the Binary Tree with maximum element in each path greater than or equal to K
- Minimum steps to reach a destination
- Number of decisions to reach destination
- Minimum possible modifications in the matrix to reach destination
- Count number of ways to reach destination in a maze