Graph – Print all paths between source and destination

Objective: Given a graph, source vertex and destination vertex. Write an algorithm to print all possible paths between source and destination.

This problem also known as “Print all paths between two nodes”

Example:

Approach: Use Depth First Search

  1. Start from the source vertex and visit the next vertex (use adjacency list).
  2. Now if you look carefully, the new problem is to find paths from the current vertex to destination. For instance as per the example above, start from vertex 0 and visit vertex 1. Now all the paths from vertex 1 to vertex 5 will be included in our final result if we add vertex 0. So make a recursive call with source as vertex 1 and destination as vertex 5.
  3. Keep track of visited nodes to avoid cycles.
  4. Add current vertex to result (taking string here) to keep track of path from source.
  5. Once reach to the destination vertex, print the path.
  6. Now visit the next node in adjacency list in step 1 and repeat all the steps (loop)
  7. See the code for more understanding.

Code:

Output:

->0->1->2->3->4->5
->0->1->3->4->5
->0->2->3->4->5

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: