簡體   English   中英

在一般樹中找到從根節點到給定節點的所有路徑

[英]Find all the paths from the root node to the given node in a general tree

我想在通用樹中找到從根節點到給定節點的所有路徑。 樹是多層次結構樹,其中可能有圓圈。 例如我有這樣的數據

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算法,但它只給了我最短的路徑,而且似乎過大了。 有人可以建議更簡單的方法來找到它們嗎? 謝謝

似乎是一個遞歸函數,它只需要歷史記錄中沒有重復的節點。 像這樣:

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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM