首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DFS在向下遍历时不会命中每个节点

DFS在向下遍历时不会命中每个节点
EN

Stack Overflow用户
提问于 2015-11-20 11:38:45
回答 1查看 85关注 0票数 0

我正在尝试计算有向无环图中最长的节点链。

我正在尝试做的事情如下:

代码语言:javascript
复制
for (Node n: nodes){
    max[n.index] = depth-first-search(n);
}

public static int depth-first-search(Node n){
    for (Node neighbor:n.Neighbors){
        return 1 + depth-first-search(neighbor);
    }
    return 0; //if no neighbors, return 0
}

因此,我们测试一些输入:

代码语言:javascript
复制
Vertex -> Neighbors
Node 1 -> 3
Node 2 -> 0
Node 3 -> 2
Node 4 -> 1, 2, 7
Node 5 -> 3, 1
Node 6 -> 4
Node 7 -> 0

现在我们用每个顶点的最长邻居链填充一个数组,所以如果我们手动完成,我们会得到以下结果:

代码语言:javascript
复制
Node 1 = Length of 2 (3, 2)
Node 2 = Length of 0
Node 3 = Length of 1 (2)
Node 4 = Length of 4 (3, 2, 1, 7)
Node 5 = Length of 3 (2, 3, 1)
Node 6 = Length of 5 ( 2, 3, 1, 4, 7) <-Longest 
Node 7 = Length of 0

如果我在我的程序中运行它,数组看起来像这样:

代码语言:javascript
复制
Node 1 = Length of 2 <- Correct
Node 2 = Length of 0 <- Correct
Node 3 = Length of 1 <- Correct
Node 4 = Length of 3 <- Off by 1
Node 5 = Length of 2 <- Off by 1
Node 6 = Length of 4 <- Off by 1
Node 7 = Length of 0 <- Correct

我继续跟踪Node 6的算法,注意到它忽略了Node 7。跟踪如下:

代码语言:javascript
复制
dfs(6)
   return 1+dfs(4)
      return 1+ dfs(1)
        return 1+ dfs(3)
         return 1+ dfs(2)
          return 0 

正如我们所看到的,它从来没有命中节点7,我也不清楚为什么。我试着在depth-first-search()中将行"return 0“改为"return 1”,它确实将长度减少了1,但它将所有以前正确的长度都改成了1。如果有人能提供一些帮助,我将非常感激。

EN

回答 1

Stack Overflow用户

发布于 2015-11-20 11:56:18

由于return语句,您只能看到一个邻居。你需要检查所有的邻居。

代码语言:javascript
复制
public static int depth-first-search(Node n){
    int max = 0; //if no neighbors, return 0
    for (Node neighbor:n.Neighbors){
        max = Math.max(max, 1 + depth-first-search(neighbor));
    }
    return max;
}

更新:

我不认为你的预期答案是正确的:

代码语言:javascript
复制
Node 1 = Length of 2 (3, 2)
Node 2 = Length of 0
Node 3 = Length of 1 (2)
Node 4 = Length of 4 (3, 2, 1, 7)
Node 5 = Length of 3 (2, 3, 1)
Node 6 = Length of 5 ( 2, 3, 1, 4, 7) <-Longest 
Node 7 = Length of 0

正确的解决方案应该是

代码语言:javascript
复制
Node 1 = Length of 2 (3 -> 2)
Node 2 = Length of 0 ()
Node 3 = Length of 1 (2)
Node 4 = Length of 3 (1 -> 3 -> 2)
Node 5 = Length of 3 (1 -> 3 -> 2)
Node 6 = Length of 4 (4 -> 1 -> 3 -> 2) <-Longest 
Node 7 = Length of 0 ()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33818561

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档