繁体   English   中英

图:DFS访问和Java实现

[英]Graphs: DFS visit and Java implementation

我正在尝试以Java语言实现对图的递归深度优先搜索。

假设条件

  • 该图用邻接表表示。

  • GraphSearchImpl是一种存储访问结果的数据结构。

  • GraphSearchImpl包含用于存储每个顶点的开始/结束时间,访问状态(UNDISCOVERED,DISCOVERED,CLOSED),路径权重等的数组。

  • 所有顶点在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的儿子。

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

请提出建议。

问题是time是一个局部变量,因此在递归中将其递增timeAtime不受影响。 您应该将其转换为全局/静态变量,或者创建一个整数包装器类,并将其传递给可变对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM