检查图是否在DFS中是循环的; isCyclic方法的输入是List <type>的源和List <type>的目标

时间:2019-03-08 03:21:45

标签: java graph depth-first-search cyclic

因此,我需要帮助来创建一个带两个参数(srcData和dstData)的DFS方法,以及一个名为isCyclic的方法,该方法使用DFS检查该图是否为循环图。这是我当前的DFS代码:

public LinkedList<Type> DFS(Type srcData, Type dstData) throws IllegalArgumentException {
    if(!this.getSources().contains(srcData) || !this.getDestinations().contains(dstData))
        throw new IllegalArgumentException();
    Vertex start = vertices.get(srcData);
    Vertex goal = vertices.get(dstData);
    start.visited = true;

    LinkedList<Vertex> stack = new LinkedList<Vertex>();
    LinkedList<Type> result = new LinkedList<Type>();
    stack.offer(start);
    Vertex end = null;
    while(stack.size() != 0)  {
        Vertex v = stack.removeLast();
        if(v.getElement().equals(dstData)) {
            end = v;
        }
        if(!v.visited) {
            v.visited = true;

            for(Edge e : v.getEdge()) {
                Vertex neighbor = e.getOtherVertex();
                if(!neighbor.visited) {
                    neighbor.cameFrom = v;
                    stack.addLast(neighbor);
                }
            }
        }
    }
    while(end != null) {
        result.addFirst(end.getElement());
        end = end.cameFrom;
    }
    return result;
}

然后我的isCyclic代码如下:

public static <Type> boolean isCyclic(List<Type> sources, List<Type> destinations) throws IllegalArgumentException {
    if(sources.size() != destinations.size())
        throw new IllegalArgumentException();

    Graph<Type> gra = new Graph<Type>();
    for(int i = 0; i < sources.size(); i++) {
        gra.addEdge(sources.get(i), destinations.get(i));
    }

    for(Type t: sources) {
        if(gra.DFS_2(t, t))
            return true;
    }

    return false;
}

0 个答案:

没有答案