【问题标题】:How to get all paths from leaf to the root in a special graph如何在特殊图中获取从叶子到根的所有路径
【发布时间】:2020-03-29 20:26:23
【问题描述】:

我正在尝试以图形形式在特殊数据结构中实现算法。我的目标是获取从叶子(目标元素)到根的所有路径。 图表如下图所示。

【问题讨论】:

    标签: java algorithm data-structures graph


    【解决方案1】:

    我们需要记住我们拥有的所有路径,以便以图表上的所有不同方式遍历,因此只有状态列表是不够的,我们需要一个路径列表。对于每条路径,如果它有一个父级,我们会将其加长一个,如果它有两个或更多,我们将复制此列表并将父级添加到每个路径。

    好吧,我不擅长 Java,我不能运行这段代码,所以我不能保证它会运行,但算法没问题。

    public static List<ARGState> getAllErrorStatesReversed(ReachedSet reachedSet) {
      ARGState pIsStart =
          AbstractStates.extractStateByType(reachedSet.getFirstState(), ARGState.class);
      ARGState pEnd = targetStates.get(0);
    
      List<List<ARGState>> results = new ArrayList<>();
      List<List<ARGState>> paths = new ArrayList<>();
    
      paths.add(new ArrayList<ARGState>(pEnd));
    
      // This is assuming from each node there is a way to go to the start
      // Go on until all the paths got the the start
      while (!paths.empty()) {
        // Expand the last path on your list
        List<ARGState> curPath = paths.remove(paths.size() - 1);
        // If there is no more to expand - add this path and continue
        if (curPath.get(curPath.size() - 1) == pIsStart) {
          results.append(curPath);
          continue;
        }
    
        // Expand the path
        Iterator<ARGState> parents = curPath.get(curPath.size() - 1).getParents().iterator();
        // Add all parents
        while (parentElement.hasNext()) {
          ARGState parentElement = parents.next();
          List<ARGState> tmp = new ArrayList<ARGState>(List.copyOf(curPath));
          tmp.add(parentElement);
          paths.add(tmp);
        }
      }
      return results;
    }
    

    希望你能理解,多多欢迎提问。
    祝你好运

    【讨论】:

    • 谢谢。所有这些都应该在我的实现中发生,对吧?
    • 我得到了输出结果[id:0,Parents[]],[id:0,Parents[]],[id:0,Parents[]] 所以只有第一个元素的列表。 :(
    • 好吧,我无法运行它,所以我无法帮助您调试。希望你理解算法。
    • 是的,它应该是正确的 3 次,因为有 3 条路径。我们如何才能进入讨论聊天?
    • 你应该考虑EV这两个术语的时间复杂度,因为算法是BFS,它是一个图算法。通常BFS的时间复杂度是O(E + V),但现在我们需要将所有不同的路径O(E*V)保存在复杂度中。
    猜你喜欢
    • 1970-01-01
    • 2018-01-29
    • 2015-10-03
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多