简体   繁体   English

深度优先搜索算法

[英]depth first search algorithm

I want to reach node Y of this tree but this code traversal whole tree. 我想要到达此树的节点Y,但此代码遍历整个树。 what changes should i do to achieve my goal? 我应该做些什么改变来实现我的目标? how to show traveled path at each step of traversal? 如何在遍历的每一步显示行进路径? I use depth first search. 我使用深度优先搜索。 thanks for any help. 谢谢你的帮助。

class Graph
{
int V;    // No. of vertices
list<int> *adj;    
void DFSUtil(int v, bool visited[]);  
public:
Graph(int V);   
void addEdge(int v, int w);  
void DFS(int v);  
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
 void Graph::DFSUtil(int v, bool visited[])
{
visited[v] = true;
cout << v << " ";
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
    if (!visited[*i])
        DFSUtil(*i, visited);
}
void Graph::DFS(int v)
{
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
    visited[i] = false;
DFSUtil(v, visited);
}
int main()
{
Graph g(25);
g.addEdge(0, 1);
g.addEdge(0, 2);
//...
return 0;
}

在此输入图像描述

Graph :: DFSUtil应该返回一个“found”标志,以及到目前为止遍历的遍历节点列表,每次检测到“found == true”时都可以扩展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM