Given an undirected and unweighted graph and two nodes as source and destination, the task is to print all the paths of the shortest length between the given source and destination.
Approach: The is to do a Breadth First Traversal (BFS) for a graph. Below are the steps:
- Start BFS traversal from source vertex.
- While doing BFS, store the shortest distance to each of the other nodes and also maintain a parent vector for each of the nodes.
- Make the parent of source node as “-1”. For each node, it will store all the parents for which it has the shortest distance from the source node.
- Recover all the paths using parent array. At any instant, we will push one vertex in the path array and then call for all its parents.
- If we encounter “-1” in the above steps, then it means a path has been found and can be stored in the paths array.
Below is the implementation of the above approach:
0 1 3 5 0 2 3 5 0 1 4 5
Time Complexity: O(V + E) where V is the number of vertices and E is the number of edges.
Auxiliary Space: O(V) where V is the number of vertices.
- Print all paths from a given source to a destination
- Print all paths from a given source to a destination using BFS
- 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 paths from all vertices to a 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 with even number of Edges from Source to Destination
- Check if given path between two nodes of a graph represents a shortest paths
- Minimum time required to transport all the boxes from source to the destination under the given constraints
- Building an undirected graph and finding shortest path using Dictionaries in Python
- Shortest cycle in an undirected unweighted graph
- Count all possible walks from a source to a destination with exactly k edges
- Multi Source Shortest Path in Unweighted Graph
- Number of shortest paths in an unweighted and directed graph
- Print all the cycles in an undirected graph
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Convert undirected connected graph to strongly connected directed graph
- 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
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.