Search in sources :

Example 1 with FloydWarshallShortestPaths

use of org.jgrapht.alg.FloydWarshallShortestPaths in project presto by prestodb.

the class QueryQueueRuleFactory method shortestCycle.

private static List<String> shortestCycle(DirectedGraph<String, DefaultEdge> graph) {
    FloydWarshallShortestPaths<String, DefaultEdge> floyd = new FloydWarshallShortestPaths<>(graph);
    int minDistance = Integer.MAX_VALUE;
    String minSource = null;
    String minDestination = null;
    for (DefaultEdge edge : graph.edgeSet()) {
        String src = graph.getEdgeSource(edge);
        String dst = graph.getEdgeTarget(edge);
        // from dst to src
        int dist = (int) Math.round(floyd.shortestDistance(dst, src));
        if (dist < 0) {
            continue;
        }
        if (dist < minDistance) {
            minDistance = dist;
            minSource = src;
            minDestination = dst;
        }
    }
    if (minSource == null) {
        return null;
    }
    GraphPath<String, DefaultEdge> shortestPath = floyd.getShortestPath(minDestination, minSource);
    List<String> pathVertexList = Graphs.getPathVertexList(shortestPath);
    // note: pathVertexList will be [a, a] instead of [a] when the shortest path is a loop edge
    if (!Objects.equals(shortestPath.getStartVertex(), shortestPath.getEndVertex())) {
        pathVertexList.add(pathVertexList.get(0));
    }
    return pathVertexList;
}
Also used : FloydWarshallShortestPaths(org.jgrapht.alg.FloydWarshallShortestPaths) DefaultEdge(org.jgrapht.graph.DefaultEdge)

Aggregations

FloydWarshallShortestPaths (org.jgrapht.alg.FloydWarshallShortestPaths)1 DefaultEdge (org.jgrapht.graph.DefaultEdge)1