Given a digraph (directed graph), find the total number of routes to reach the destination from a given source with exactly m edges.

For example, consider the following graph:

 
Find number of routes in diagraph

Let source = 0, destination = 3, number of edges m = 4. The graph has 3 routes from source 0 to destination 3 with 4 edges. The solution should return the total number of routes 3.

0 —> 1 —> 5 —> 2 —> 3
0 —> 1 —> 6 —> 5 —> 3
0 —> 6 —> 5 —> 2 —> 3

Practice this problem

The idea is to do a BFS traversal from the given source vertex. BFS is generally used to find the shortest paths in graphs/matrices, but we can modify normal BFS to meet our requirements. Usually, BFS doesn’t explore already discovered vertices again, but here we do the opposite. To cover all possible paths from source to destination, remove this check from BFS. But if the graph contains a cycle, removing this check will cause the program to go into an infinite loop. We can easily handle that if we don’t consider nodes having a BFS depth of more than m. Basically, we maintain two things in the BFS queue node:

  • The current vertex number.
  • The current depth of BFS (i.e., how far away from the current node is from the source?).

So, whenever the destination vertex is reached and BFS depth is equal to m, we update the result. The BFS will terminate when we have explored every path in the given graph or BFS depth exceeds m. Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

3

Java


Download  Run Code

Output:

3

Python


Download  Run Code

Output:

3

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