图:DFS 访问和 Java 实施

Graphs: DFS visit and Java implementation

我正在尝试使用 Java 语言对图实施递归深度优先搜索。

假设

代码

    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的start/end时间间隔必须包含在A的时间间隔中,因为B在这个图中是A的儿子。

我知道问题是我没有正确使用时间计数器。

求推荐。

问题在于 time 是一个局部变量,因此当您在递归中递增它时,Atime 不受影响。您应该将其转换为 global/static 变量,或者制作一个整数包装器 class 并通过可变对象传递它。