【问题标题】:DFS: Print all complete pathsDFS:打印所有完整路径
【发布时间】:2021-06-11 23:23:20
【问题描述】:

Below 函数打印所有子路径。是否可以只显示完整的路径,即 A->B->C(包括下面的 REQUIRED OUTPUT)。

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

【问题讨论】:

  • 好吧,从逻辑上考虑代码。为什么它会给你它给你的输出?你能想到在print 语句应该运行时是真的,而不是每次应该被抑制时都不是真的吗?你能想出一种在代码中进行测试的方法吗?

标签: java algorithm recursion depth-first-search


【解决方案1】:

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

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

【讨论】:

  • 谢谢它打印了我想要的输出
猜你喜欢
  • 2018-03-04
  • 2019-07-21
  • 1970-01-01
  • 2016-04-22
  • 1970-01-01
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-04
相关资源
最近更新 更多