实现深度优先图遍历

发布于 2024-11-02 23:27:21 字数 534 浏览 4 评论 0原文

我有关于深度优先遍历的相互矛盾的信息,并且可以使用一些帮助来理解如何构建程序。给定某个图,我想打印一系列顶点。用户将输入一个特定的节点来开始遍历。我正在查看不同的示例,但我不明白深度优先遍历的顺序是如何工作的。我有以下伪代码可以使用:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嘦怹 2024-11-09 23:27:21

这两个片段的关键在于以下想法:

check if item found at (v)
if item not found,
   for all vertices u adjacent to v
     depth_first_search(u)

您不必立即检查所有节点 (v) 子节点(u 的列表)的结束条件,而是仅在当前节点 v 处检查它。如果结束条件如果不满足,则从 v 的第一个子级 u1 开始应用相同的深度优先搜索函数。由于 u1 也可能有子级,因此在处理 v 的其余子级之前,将应用完全相同的函数到 u1 的子级,依此类推。这就是为什么它被称为深度优先搜索,因为您的搜索将首先搜索路径中可能的最低子代集,然后返回检查剩余的子代。

The key to both of these snippets are the following idea:

check if item found at (v)
if item not found,
   for all vertices u adjacent to v
     depth_first_search(u)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文