[英]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.