Java DFS:打印所有完整的路径
下面的函数打印所有子路径。是否可以只显示完整的路径,即A->B->C(包括下面所需的输出)Java DFS:打印所有完整的路径,java,algorithm,recursion,depth-first-search,Java,Algorithm,Recursion,Depth First Search,下面的函数打印所有子路径。是否可以只显示完整的路径,即A->B->C(包括下面所需的输出) 您可以在打印前添加一个条件,以检查您是否位于路径的末尾: findPaths(List<Integer>[] adjacencyList, int u, List<String> path) throws IOException { if (adjacencyList[u].isEmpty()) { print(path+" &quo
您可以在打印前添加一个条件,以检查您是否位于路径的末尾:
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));
}
}
}
findpath(List[]adjacencyList,int u,List path)引发IOException{
if(adjacencyList[u].isEmpty()){
打印(路径+“”+path.size()+“\n”);
}
否则{
for(整数v:邻接列表[u]){
add(mapIndexToCode.get(v));
FindPath(邻接列表、v、路径、编写器);
remove(mapIndexToCode.get(v));
}
}
}
好吧,从逻辑上考虑代码。为什么它给你它给你的输出?当print
语句运行时,您能想到一些是正确的,而不是每次被抑制时都是正确的吗?你能想出一种在代码中测试的方法吗?谢谢,它打印了我想要的输出
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));
}
}
}