实现深度优先图遍历
我有关于深度优先遍历的相互矛盾的信息,并且可以使用一些帮助来理解如何构建程序。给定某个图,我想打印一系列顶点。用户将输入一个特定的节点来开始遍历。我正在查看不同的示例,但我不明白深度优先遍历的顺序是如何工作的。我有以下伪代码可以使用:
public DFS() {
DFS(v)
{ num(v) = i ++;
for all vertices u adjacent to v
{ if num(u) is 0
attach edge(uv) to edges;
DFS(u);
}
}
depthFirstSearch()
{ for all vertices v
num(v) = 0;
edges = null; //vector of all edges
i=1;
while there is a vertex v such that num(v) is 0
DFS(v);
output edges;
}
I have conflicting information about depth first traversal and could use some help in understanding how to build a program. Given a certain graph, I want to print a sequence of vertices. The user will input a particular node to start the traversal from. I am looking at different examples and I don't understand how the order of the depth-first traversal works. I have the following pseudocode to work with:
public DFS() {
DFS(v)
{ num(v) = i ++;
for all vertices u adjacent to v
{ if num(u) is 0
attach edge(uv) to edges;
DFS(u);
}
}
depthFirstSearch()
{ for all vertices v
num(v) = 0;
edges = null; //vector of all edges
i=1;
while there is a vertex v such that num(v) is 0
DFS(v);
output edges;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这两个片段的关键在于以下想法:
您不必立即检查所有节点 (v) 子节点(u 的列表)的结束条件,而是仅在当前节点 v 处检查它。如果结束条件如果不满足,则从 v 的第一个子级 u1 开始应用相同的深度优先搜索函数。由于 u1 也可能有子级,因此在处理 v 的其余子级之前,将应用完全相同的函数到 u1 的子级,依此类推。这就是为什么它被称为深度优先搜索,因为您的搜索将首先搜索路径中可能的最低子代集,然后返回检查剩余的子代。
The key to both of these snippets are the following idea:
Instead of checking for the end condition at all the node's (v) children (list of u's) right away, you only check for it at the current node v. If the end condition is not met, you apply the same depth first search function starting with the first child of v, u1. Since u1 might also have children, the exact same function will be applied to u1's children before the remainder of v's children are processed, and so on. This is why it is called a depth first search, since your search will first search to the lowest possible set of children in a path before coming back to check the remaining children.