Solution: Count the Paths Between Two Nodes
This review provides the solution to printing all the paths between two nodes.
We'll cover the following...
We'll cover the following...
Solution
Java
Files
class Count {public static int countPaths(Graph g, int start, int destination){int count = 0;return countPathsRecursive(g, start, destination, count);}public static int countPathsRecursive(Graph g, int start, int destination, int count) {LinkedList < Integer > Llist[];Llist = g.getAdj();//checking if destination is reached meaning 1 path availableif (start == destination) {count++;}else {//Find paths from adjacent verticesfor (int i = 0; i < Llist[start].size(); i++) {int ajdacentVertex = Llist[start].get(i);count = countPathsRecursive(g, ajdacentVertex, destination, count);}}return count;}}class Main {public static void main(String args[]) {int answer;Graph g1 = new Graph(6);g1.addEdge(0, 1);g1.addEdge(0, 2);g1.addEdge(1, 2);g1.addEdge(1, 3);g1.addEdge(3, 4);g1.addEdge(2, 3);g1.addEdge(4, 5);answer = Count.countPaths(g1, 0, 5);System.out.println(answer);Graph g2 = new Graph(7);g2.addEdge(0, 1);g2.addEdge(1, 2);g2.addEdge(1, 5);g2.addEdge(2, 3);g2.addEdge(2, 4);g2.addEdge(5, 3);g2.addEdge(5, 6);g2.addEdge(3, 6);answer = Count.countPaths(g2, 0, 3);System.out.println(answer);}}
Explanation
Let’s try to think recursively about the solution to this problem. Take a concrete example where the source node has three adjacent nodes. These nodes report that they have 2, 3, and 4 paths to the destination node, respectively. Then, the total number of paths from the source node to the destination should be 2 + 3 + 4 = 9. Therefore, for any given node, the recursive way to compute the number of paths to ...