Count all possible paths between two vertices
Count the total number of ways or paths that exist between two vertices in a directed graph. These paths don’t contain a cycle, the simple enough reason is that a cycle contains an infinite number of paths and hence they create a problem.
For the following Graph:Input: Count paths between A and E
Output : Total paths between A and E are 4
Explanation: The 4 paths between A and E are:
A -> E
A -> B -> E
A -> C -> E
A -> B -> D -> C -> E
Input : Count paths between A and C
Output : Total paths between A and C are 2
Explanation: The 2 paths between A and C are:
A -> C
A -> B -> D -> C
The problem can be solved using backtracking, that says take a path and start walking on it and check if it leads us to the destination vertex then count the path and backtrack to take another path. If the path doesn’t lead to the destination vertex, discard the path.
This type of graph traversal is called Backtracking.
Backtracking for above graph can be shown like this:
The red color vertex is the source vertex and the light-blue color vertex is destination, rest are either intermediate or discarded paths.
This give four paths between source(A) and destination(E) vertex.
Why this solution will not work for a graph which contains cycles?
The Problem Associated with this is that now if one more edge is added between C and B, it would make a cycle (B -> D -> C -> B). And hence after every cycle through the loop, the length path will increase and that will be considered as a different path, and there would be infinitely many paths because of the cycle.
Create a recursive function that takes index of node of a graph and the destination index. Keep a global or a static variable count to store the count.
If the current nodes is the destination increase the count.
Else for all the adjacent nodes, i.e. nodes that are accessible from the current node, call the recursive function with the index of adjacent node and the destination.