【问题标题】:Cycle detection in directed Graph using DFS based on stack使用基于堆栈的 DFS 在有向图中进行循环检测
【发布时间】:2017-05-02 16:42:53
【问题描述】:

以下算法在堆栈溢出异常后失败。请让我知道如何纠正它以在有向图中进行循环检测,或者如果可能的话,有人可以提供基于堆栈而不是递归的算法。

public boolean hasCycle(Graphnode<T> n) {

    n.setMark(IN_PROGRESS);

    for (Graphnode<T> m : n.getSuccessors()) {
        if (m.getMark() == IN_PROGRESS) {
            return true;
        }

        if (m.getMark() != DONE) {
            if (hasCycle(m)) {
                return true;
              }
        }
    }

    n.setMark(DONE);

    return false;
}

谢谢, 维克兰特

【问题讨论】:

  • 如果我的回答对您有帮助,请随时将此问题标记为已解决

标签: java graph directed-acyclic-graphs microsoft-distributed-file-system


【解决方案1】:

我很久没有做过这种事情了,但是你的代码看起来很奇怪。 你的第一个 if 条件是:

if (m.getMark() == IN_PROGRESS) {

return true;
}

我认为应该是这样的:

if (m.getMark() == IN_DONE) {

return true;
}

如果不是,m.getMark() == IN_PROGRESSm.getMark() != DONE 有什么区别?您的第二个 if 条件永远不会被触发。

注意:如果你通过 SO,你会发现许多算法使用 DFS 或堆栈...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 2018-08-19
    • 2016-01-27
    • 2017-01-19
    • 1970-01-01
    相关资源
    最近更新 更多