【发布时间】: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