【发布时间】:2018-06-05 13:45:30
【问题描述】:
我正在尝试用 Java 语言实现对图形的递归深度优先搜索。
假设
图形用邻接表表示。
GraphSearchImpl 是一种存储访问结果的数据结构。
GraphSearchImpl 包含存储每个顶点的开始/结束时间、访问状态(未发现、已发现、已关闭)、路径权重等的数组。
所有顶点都有一个映射在 HashMap 中的唯一索引,其中 String 是每个顶点的唯一标签。我正在使用此索引为指定的顶点读取/写入数组单元格。
代码
public void visitDFSRecursive(GraphSearchImpl search,VertexImpl u,Integer time) {
int index = search.getIndexOf(u);
search.status[index]=VertexImpl.DISCOVERED;
time++;
search.startTimes[index]=time;
for (VertexImpl v: u.getAdjList()) {
int adjIndex = search.getIndexOf(v);
if (search.status[adjIndex]==VertexImpl.UNDISCOVERED) {
search.status[adjIndex]=VertexImpl.DISCOVERED;
search.parents[adjIndex]=u;
visitDFSRecursive(search,v,time);
}
}
search.status[index]=VertexImpl.CLOSED;
time++;
search.endTimes[index]=time;
}
我在一个只有两个节点 (A -> B) 的图形上这样调用这个方法:
g.visitDFSRecursive(search,sourceVertex,new Integer(0));
输出如下:
-A 开始于 1 结束于 2
-B 开始于 2 结束于 3
这显然是错误的,因为B的开始/结束的时间间隔必须包含在A的时间间隔中,因为在这个图中B是A的儿子。
我知道问题是我没有正确使用计时器。
请提出建议。
【问题讨论】:
标签: java recursion graph depth-first-search