DFS:打印所有完整路径

问题描述

下面的函数打印所有子路径。是否可以仅显示完整路径,即 A->B->C(包括下面的必需输出)。

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

解决方法

您可以在打印前添加一个条件来检查您是否在路径的末尾:

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));
        }
        }
    }