Given a directed graph, a source vertex ‘src’ and a destination vertex ‘dst’, print all paths from given ‘src’ to ‘dst’.
Consider the following directed graph. Let the src be 2 and dst be 3. There are 3 different paths from 2 to 3.
We have already discussed Print all paths from a given source to a destination using DFS.
Below is BFS based solution.
create a queue which will store path(s) of type vector initialise the queue with first path starting from src Now run a loop till queue is not empty get the frontmost path from queue check if the lastnode of this path is destination if true then print the path run a loop for all the vertices connected to the current vertex i.e. lastnode extracted from path if the vertex is not visited in current path a) create a new path from earlier path and append this vertex b) insert this new path to queue
path from src 2 to dst 3 are 2 0 3 2 1 3 2 0 1 3
This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
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
- Print all shortest paths between given source and destination in an undirected graph
- 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
- Minimum steps to reach a destination
- Sudo Placement[1.3] | Final Destination
- Minimum possible modifications in the matrix to reach destination
- Find the minimum cost to reach destination using a train
- Count number of ways to reach destination in a Maze using BFS
- Find if there is a path of more than k length from a source
- Minimum distance to the corner of a grid from source
- Multi Source Shortest Path in Unweighted Graph
- D'Esopo-Pape Algorithm : Single Source Shortest Path