Given a directed graph and two vertices (say source and destination vertex), determine if the destination vertex is reachable from the source vertex or not. If a path exists from the source vertex to the destination vertex, print it.

For example, there exist two paths [0—3—4—6—7] and [0—3—5—6—7] from vertex 0 to vertex 7 in the following graph. In contrast, there is no path from vertex 7 to any other vertex.

Directed Graph

Practice this problem

We can use the Breadth–first search (BFS) algorithm to check the connectivity between any two vertices in the graph efficiently. The idea is to start the BFS routine from the source vertex and check if the destination vertex is reached during the traversal. If the destination vertex is not encountered at any point, we can say that it’s not reachable from the source vertex.

This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

Path exists from vertex 0 to vertex 7

Java


Download  Run Code

Output:

Path exists from vertex 0 to vertex 7

Python


Download  Run Code

Output:

Path exists from vertex 0 to vertex 7

How to print the complete path?

The idea is to store the complete path between the source and destination vertex in an array using recursion. We can easily achieve this if using Depth–first search (DFS) to determine the path between the vertices. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

Path exists from vertex 0 to vertex 7
The complete path is 0 3 4 6 7

Java


Download  Run Code

Output:

Path exists from vertex 0 to vertex 7
The complete path is [0, 3, 4, 6, 7]

Python


Download  Run Code

Output:

Path exists from vertex 0 to vertex 7
The complete path is [0, 3, 4, 6, 7]

The time complexity of the above solutions is O(V + E), where V and E are the total number of vertices and edges in the graph, respectively.

 
Exercise: Extend the solution to print all paths between given vertices (solution link)