java - 如何找到列表的所有路径?

标签 java algorithm graph

我有一个这样的列表:

[[A], [B, C, D], [E, F], [G]]

对于 Java 代码初始化:

 List<List<String>> data = new ArrayList<>();
 data.add(Arrays.asList("A"));
 data.add(Arrays.asList("B", "C", "D"));
 data.add(Arrays.asList("E", "F"));
 data.add(Arrays.asList("G"));

并希望得到如下结果:

[[A,B,E,G],[A,B,F,G], [A,C,E,G],[A,C,F,G],[A,D,E,G],[A,D,F,G]]

怎么做?非常感谢。

最佳答案

你可以写一个递归算法来解决这个问题。对于每个递归调用,该算法在图中向下移动一层。它的要点是首先计算当前所在层下的所有路径,然后将当前层中的所有节点添加到这些路径。

这里有一些伪代码可以让你继续:

paths(input) {
    if input is empty -> return empty // This is your base case

    currentNodes = input[0]
    subPaths = paths(input.tail) // Recursive call with the rest of your input

    if subPaths is empty -> return input // The paths from the last layer is itself

    result = emptyList()
    for all nodes in currentNodes
        for all paths in subPaths
            prepend node to path and add to result

    return result
}

关于java - 如何找到列表的所有路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55195012/

相关文章:

ios - 如何在 Shinobi Charts 中将条形宽度设置为固定值?

graph - 如何在JanusGraph中将权重与系数求和?

Java套接字: NTP application always return null string

Java 3D LWJGL 碰撞

algorithm - 数字数组的最优冒泡排序算法

java - 确定二进制数的间隙长度

python - 如何在 matplotlib.pyplot 中设置 X 和 Y 轴标题

java - Gradle Proguard 优化时出现大量内存错误

java - onKeyDown 在我的 fragment 代码中不起作用

sql-server - 给定一个字节数组,我如何找出使用了哪种压缩算法?