我想在常规树中找到从根节点到给定节点的所有路径。树是一个多层次树,可能有圆圈。例如,我有这样的数据
a b
a c
a z
b e
b d
e f
f e
c g
e g
g h
我想获得从a到h的所有路径。
的两个路径是上述示例的结果a a
b c
e g
g h
h
我尝试过Dijkstras算法,但它只能让我获得最短的路径,但它似乎有点过分。任何人都可以建议更容易找到它们吗?感谢
答案 0 :(得分:0)
看起来像一个递归函数,它只允许历史记录中没有重复的节点。像这样:
public class FindPath {
public static void main(String [] args) {
Node a = new Node("a");
Node b = new Node("b");
Node c = new Node("c");
Node d = new Node("d");
Node e = new Node("e");
Node f = new Node("f");
Node g = new Node("g");
Node h = new Node("h");
Node z = new Node("z");
a.add(b); a.add(c); a.add(z);
b.add(e); b.add(d);
e.add(f); e.add(g);
f.add(e);
c.add(g);
g.add(h);
ArrayList<ArrayList<Node>> viablePaths = new ArrayList<ArrayList<Node>>();
findPaths(a, "h", new ArrayList<Node>(), viablePaths);
for (ArrayList<Node> path: viablePaths) {
print(path);
}
}
public static void findPaths(Node start, String endName, ArrayList<Node> startingPath, ArrayList<ArrayList<Node>> viablePaths) {
startingPath.add(start);
for (Node next: start.children) {
ArrayList<Node> extendedPath = (ArrayList<Node>) startingPath.clone();
if (next.equals(endName)) {
extendedPath.add(next);
viablePaths.add(extendedPath);
} else {
boolean nodeAlreadyUsed = false;
for (Node existingNode: startingPath) {
if (next.equals(existingNode)) nodeAlreadyUsed = true;
}
if (!nodeAlreadyUsed) {
findPaths(next, endName, extendedPath, viablePaths);
}
}
}
}
public static void print(ArrayList<Node> path) {
StringBuffer sb = new StringBuffer();
for (Node node: path) sb.append(node + " ");
System.out.println(sb);
}
}
class Node {
public String name;
public ArrayList<Node> children = new ArrayList<Node>();
public Node(String name) {this.name = name;}
public boolean equals (Node other) {return other.name.equals(name);}
public boolean equals (String other) {return other.equals(name);}
public void add(Node child) {children.add(child);}
public String toString() {return name;}
}
这将打印:
a b e g h
a c g h