All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.uni.freiburg.iig.telematik.jagal.graph.GraphUtils Maven / Gradle / Ivy

Go to download

JAGAL provides implementations for directed graphs (weighted and unweighted) and various types of transition systems as well as utils for graph traversal and modification.

The newest version!
package de.uni.freiburg.iig.telematik.jagal.graph;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;

import de.uni.freiburg.iig.telematik.jagal.graph.abstr.AbstractGraph;
import de.uni.freiburg.iig.telematik.jagal.graph.exception.EdgeNotFoundException;
import de.uni.freiburg.iig.telematik.jagal.graph.exception.GraphException;

public class GraphUtils {

    private final static ArrayBlockingQueue queue = new ArrayBlockingQueue<>(10);
    private final static Set visited = new HashSet<>();

    /**
     * Checks, if there is a closed cycle in the graph with Node<T>
     * baseNode<T>, using inEdge and outEdge.
     *
     * @param  Type of the vertex
     * @param  Type of the edge
     * @param  Type of the graph's elements
     * @param graph The graph to check.
     * @param baseVertexName The base Node<T> for cycle check
     * @param outEdgeVertexName Incoming edge of the base Node<T> in the
     * potential cycle
     * @param inEdgeVertexName Outgoing edge of the base Node<T> in the
     * potential cycle
     * @return true if there is a closed cycle with inEdge and
     * outEdge; false otherwise.
     * @throws
     * de.uni.freiburg.iig.telematik.jagal.graph.exception.GraphException
     */
    public static , E extends Edge, U> boolean cycleBy(AbstractGraph graph, String baseVertexName, String inEdgeVertexName, String outEdgeVertexName) throws GraphException {
        if (!graph.containsEdge(inEdgeVertexName, baseVertexName)) {
            throw new EdgeNotFoundException(inEdgeVertexName, baseVertexName, graph);
        }
        if (!graph.containsEdge(baseVertexName, outEdgeVertexName)) {
            throw new EdgeNotFoundException(baseVertexName, outEdgeVertexName, graph);
        }

        visited.clear();
        queue.clear();
        queue.offer(outEdgeVertexName);
        while (!queue.isEmpty()) {
            if (queue.peek().equals(inEdgeVertexName)) {
                return true;
            }
            visited.add(queue.peek());
            // Cast is safe since only objects of type V were added to the queue
            // before.
            for (V vertex : graph.getChildren((String) queue.poll())) {
                if (!queue.contains(vertex.getName()) && !visited.contains(vertex.getName())) {
                    queue.offer(vertex.getName());
                }
            }
        }
        return false;
    }

}