Print all shortest paths between given source and destination in an undirected graph
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.
Input: source = 0, destination = 5
0 -> 1 -> 3 -> 5
0 -> 2 -> 3 -> 5
0 -> 1 -> 4 -> 5
All the above paths are of length 3, which is the shortest distance between 0 and 5.
Input: source = 0, destination = 4
0 -> 1 -> 4
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.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.