Supponendo di avere
struct Node
{
std::vector<Node *> children;
};
allora cosa si potrebbe fare è attraversare tutto l'albero a partire dalle radici mantenere l'intera catena durante l'attraversamento. Se trovi per es. Node1 quindi si salva la catena di corrente, se trovate node2 allora si controlla l'incrocio ... nel codice (il fitness):
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;
}
Vuoi dire trovare ** IL ** percorso. Se non si consente a un percorso di attraversare lo stesso nodo più volte, c'è un solo percorso da un nodo all'altro in un albero (questa è una delle possibili definizioni di albero, in realtà) – 6502
@ 6502 sì, naturalmente – Yakov
Ho postato una risposta partendo dal presupposto che sei interessato anche a percorsi parzialmente "ascendenti" anche se non ci sono collegamenti al nodo genitore di un nodo nella tua rappresentazione. Questo non è chiaro nella domanda ... – 6502