【问题标题】:Graphs: DFS visit and Java implementation图表:DFS 访问和 Java 实现
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多