如何浏览图表?

时间:2011-04-26 11:22:30

标签: java algorithm

我有以下树

     1
    2 3
   4 5 6
  7 8 9 0

现在我想通过树走过所有可能的路径。始终可以从下面的行移动到相邻的数字。例如

1 2 4 71 2 5 8

任何提示最好的方法是什么?我正在寻找一般提示,但在我的实现中,每行都有一个ArrayList。

2 个答案:

答案 0 :(得分:1)

我怀疑使用递归是最简单的方法。

类似

public static void visit(List<List<Integer>> tree, Visitor<List<Integer>> visitor) {
    visit0(tree, visitor, Collections.<Integer>emptyList());
}

private static void visit0(List<List<Integer>> tree, 
                           Visitor<List<Integer>> visitor, List<Integer> list) {
    if (tree.isEmpty()) {
       visitor.onList(list);
       return;
    }

    List<List<Integer>> tree2 = tree.subList(1, tree.size() - 1);
    List<Integer> ints = new ArrayList<Integer>(list);
    ints.add(0); // dummy entry.
    for(int n: tree.get(0)) {
        ints.set(ints.size()-1, n);
        visit0(tree2, visitor, ints);
    }
}

答案 1 :(得分:0)

我认为像本文所述的学术级解决方案:

RicardoSimões的

"APAC: An exact algorithm for retrieving cycles and paths in all kinds of graphs"

算法简述:

声称:

(a)算法找到所有简单路径。

(b)算法找到所有周期。

(c)算法终止。

(d)算法复杂度为O(Cnpaths)。 “(......)复杂性随着线性增加而增加 路径数(...)“

作者使用伪代码符号 - 我认为这是最普遍的符号之一。