[英]How to find path between two nodes on a minimum spanning tree
我有最小生成樹,我已經創建了鄰接列表。 在這個鄰接表的幫助下,我運行了 DFS 算法並且它工作正常。 問題是我想獲得兩個節點之間的路徑。 示例樹:
例如我想獲得從 4 到 6 的路徑
當前 output : 4-3-1-7-2-5-6
通緝 output : 4-3-5-6
代碼:
void Graph::DFS(int source, int destination)
{
Visited[source - 1] = true;
vector<pair<int,int>> adjList = MSTAdjacencyLists[source - 1]; //first is vertice, second is weight
cout << source << "-";
for (int i = 0; i < adjList.size(); i++)
{
if (adjList[i].first == destination)
{
cout << adjList[i].first <<"\nFound!!" << endl;
break;
}
if (Visited[adjList[i].first-1] == false)
{
DFS(adjList[i].first, destination);
}
}
}
我讀過 DFS 可能會有幫助,但也許有更好的方法?
未測試,因為沒有可用的小測試
bool Graph::DFS(int source, int destination) <<<<====== bool return
{
Visited[source - 1] = true;
vector<pair<int,int>> adjList = MSTAdjacencyLists[source - 1]; //first is vertice, second is weight
for (int i = 0; i < adjList.size(); i++)
{
if (adjList[i].first == destination)
{
cout << adjList[i].first <<"\nFound!!" << endl;
return true;
}
if (Visited[adjList[i].first-1] == false)
{
if(DFS(adjList[i].first, destination))
{
cout << source << "-";
return true;
}
}
}
return false;
}
即 DFS 指示它是否找到了目的地,當展開遞歸時打印返回 true 的路徑
不確定我們是否需要我移動的第一個“cout << source”。
幾個小時后,我設法找到了解決方案。 這篇文章對我很有幫助。 https://www.geeksforgeeks.org/print-the-path-between-any-two-nodes-of-a-tree-dfs/
使用堆棧和回溯的想法非常聰明。 解決后的代碼:
void Graph::DFS(int source, int destination, vector<int> stack)
{
Visited[source - 1] = true;
stack.push_back(source);
vector<pair<int,int>> adjList = MSTAdjacencyLists[source - 1];
for (int i = 0; i < adjList.size(); i++)
{
if (adjList[i].first == destination)
{
stack.push_back(adjList[i].first);
printPath(stack);
return;
}
if (Visited[adjList[i].first-1] == false)
{
DFS(adjList[i].first, destination,stack);
}
}
stack.pop_back();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.