简体   繁体   English

图:DFS访问和Java实现

[英]Graphs: DFS visit and Java implementation

I'm trying to implement a recursive Depth-First Search for a graph in Java language. 我正在尝试以Java语言实现对图的递归深度优先搜索。

Assumptions 假设条件

  • The graph is represented with adjacency lists. 该图用邻接表表示。

  • GraphSearchImpl is a data structure that stores the result of a visit. GraphSearchImpl是一种存储访问结果的数据结构。

  • GraphSearchImpl contains arrays that store, for each vertex, start/end times, visit status (UNDISCOVERED, DISCOVERED, CLOSED), weight of the path etc etc.. GraphSearchImpl包含用于存储每个顶点的开始/结束时间,访问状态(UNDISCOVERED,DISCOVERED,CLOSED),路径权重等的数组。

  • All vertices have a unique index mapped in a HashMap, where the String is a unique label for each vertex. 所有顶点在HashMap中映射有一个唯一索引,其中String是每个顶点的唯一标签。 I'm reading/writing arrays cells, for a specified vertex, using this index. 我正在使用此索引读取/写入指定顶点的数组单元。

Code

    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;
    }

I'm calling this method like this, over a graph with just two nodes (A -> B): 我在只有两个节点(A-> B)的图上这样调用此方法:

g.visitDFSRecursive(search,sourceVertex,new Integer(0));

The output is the following: 输出如下:

-A starts at 1 ends at 2 -A从1开始于2

-B starts at 2 ends at 3 -B从2开始于3

It's obviously wrong, because the time interval of start/end of B must be included in the A's one, since B is a son of A in this graph. 这显然是错误的,因为B的开始/结束时间间隔必须包含在A的时间间隔中,因为在此图中B是A的儿子。

I know the problem is that I'm not using time counter right. 我知道问题是我没有正确使用时间计数器。

Please suggest. 请提出建议。

The problem is that time is a local variable, so when you increment it up in your recursion, the time for A is not affected. 问题是time是一个局部变量,因此在递归中将其递增timeAtime不受影响。 You should convert it to a global/static variable, or make an integer wrapper class and pass it through a mutable object. 您应该将其转换为全局/静态变量,或者创建一个整数包装器类,并将其传递给可变对象。

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

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