簡體   English   中英

算法在無向樹中查找路徑

[英]Algorithm finding path in an undirected tree

假設我被賦予了一個無向樹,我需要在兩個節點之間找到一條路徑(唯一的路徑)。

什么是最好的算法。我可能會使用Dijkstra的算法,但樹木可能更好。

C ++示例將有所幫助,但不是必需的

謝謝

假設每個節點都有一個指向其父節點的指針,那么只需從每個起始節點向后追溯樹。 最終,兩條路徑必須相交。 測試交集可以像維護節點地址的std::map一樣簡單。

UPDATE

當您更新問題以指定無向樹時,上述內容無效。 一個簡單的方法就是從節點#1開始執行深度優先遍歷,最終你會遇到節點#2。 這是樹的大小的O(n) 假設一棵完全普通的樹,我不確定會有更快的方法。

假設你有

struct Node
{
    std::vector<Node *> children;
};

那么可以做的就是從根部開始遍歷整個樹,在遍歷期間保持整個鏈。 如果您找到例如node1然后保存當前鏈,如果找到node2,那么您在代碼( UNTESTED )中檢查交叉點...:

bool findPath(std::vector<Node *>& current_path, // back() is node being visited
              Node *n1, Node *n2,                // interesting nodes
              std::vector<Node *>& match,        // if not empty back() is n1/n2
              std::vector<Node *>& result)       // where to store the result
{
    if (current_path.back() == n1 || current_path.back() == n2)
    {
        // This is an interesting node...
        if (match.size())
        {
            // Now is easy: current_path/match are paths from root to n1/n2
            ...
            return true;
        }
        else
        {
            // This is the first interesting node found
            match = current_path;
        }
    }
    for (std::vector<Node *>::iterator i=current_path.back().children.begin(),
                                       e=current_path.back().children.end();
         i != e; ++i)
    {
        current_path.push_back(*i);
        if (findPath(current_path, n1, n2, match, result))
          return true;
        current_path.pop_back(); // *i
    }
    return false;
}

廣度優先搜索和深度優先搜索比Dijkstra算法更有效。

暫無
暫無

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

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