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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Print all paths from a given source to a destination using BFS
- 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
- 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 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 Palindromic Paths of Binary tree
- Print all possible paths from top left to bottom right of a mXn matrix
- Print all paths of the Binary Tree with maximum element in each path greater than or equal to K