【问题标题】:StackOverflowError -java堆栈溢出错误-java
【发布时间】:2014-04-18 12:55:38
【问题描述】:

我正在编写代码以在图表上运行 DFS,但是这些图表非常庞大。我在 DFS 访问时遇到堆栈溢出错误,但是其他人能够毫无问题地运行 DFS 访问。我有什么理由会收到 StackOverFlow 错误吗?我尝试分配更多内存(我有 16gb 内存),但它限制了我 1gb 内存。

public void DFSVisit(Graph <String, String> graph, String current, int [] data, StackObject [] finish, boolean complicated){
    //data stores the time
    data[9]++;
    graph.setAnnotation(current, "time", data[9]);
    graph.setAnnotation(current, "color", "gray");
    Iterator <ArrayList<String>> itr = graph.outAdjacentVertices(current);
    ArrayList <String> currentlist = null;
    String adjacent;
    while(itr.hasNext()){
        currentlist = itr.next();
        adjacent = currentlist.get(1);
            if(graph.getAnnotation(adjacent, "color").equals("white")){
                graph.setAnnotation(adjacent, "parent", current);
                DFSVisit(graph, adjacent, data, finish, complicated);
            }
    }
    graph.setAnnotation(current, "color", "black");
    data[9]++;
    graph.setAnnotation(current, "done", data[9]);
    finish[0].done.push(current);
    //System.out.println(current);
}

【问题讨论】:

  • 如果搜索空间是无限的,每个运行你的代码的系统都会得到这个异常。
  • 您必须将当前节点标记为已访问,这样您就不会从相邻的顶点列表中返回它。想象一个简单的图,它有两个顶点和一条连接它们的边。两个顶点相邻列表将相互包含,您的算法将一遍又一遍地访问它们。

标签: java graph depth-first-search stack-overflow


【解决方案1】:

分配内存无济于事。 您在同一方法中调用 DFSVisit 并且没有为该方法定义返回条件,因此它将引发 stackoverflow 错误。

【讨论】:

    【解决方案2】:

    您必须在某个点停止递归调用..在某些条件下..否则它将是无休止的调用并会引发堆栈溢出错误。

    【讨论】:

      【解决方案3】:

      请注意,DFS 的空间复杂度是 O(b.m),其中 m 是搜索空间的深度,b 是最大分支因子,所以如果 m 是无限的,你可能永远不会能够通过不适当的实现来解决问题。

      要找到更好的示例,请查看关于 SO 的 this 问题。

      【讨论】:

        【解决方案4】:

        我转而使用笔记本电脑工作,它立即工作。显然问题是我使用 32 位 Eclipse 而不是 64 位 Eclipse。我什至没有意识到我在桌面上使用的是 32 位。

        【讨论】:

          猜你喜欢
          • 2011-09-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-19
          • 2014-04-10
          • 2014-01-26
          • 2019-02-16
          • 1970-01-01
          相关资源
          最近更新 更多