Search code examples
javaalgorithmrecursiondepth-first-search

DFS: Print all complete paths


The Below function prints all the sub-paths. Is it possible to display only the complete paths i.e A->B->C (included REQUIRED OUTPUT below).

findPaths(List<Integer>[] adjacencyList, int u, List<String> path) throws IOException {
        print(path+" "+path.size()+ "\n");
        for (Integer v : adjacencyList[u]) {
            path.add(mapIndexToCode.get(v));
            findPaths(adjacencyList, v, path, writer);
            path.remove(mapIndexToCode.get(v));
        }
    }
OUTPUT
A 1
A B 2
A B C 3

E 1
E F 2
REQUIRED OUTPUT
A B C 3

E F 2

Solution

  • You can add a condition before printing to check if you are at the end of the path:

    findPaths(List<Integer>[] adjacencyList, int u, List<String> path) throws IOException {
            if (adjacencyList[u].isEmpty()) {
               print(path+" "+path.size()+ "\n");
            }
            else {
            for (Integer v : adjacencyList[u]) {
                path.add(mapIndexToCode.get(v));
                findPaths(adjacencyList, v, path, writer);
                path.remove(mapIndexToCode.get(v));
            }
            }
        }