Fast way of determining whether two nodes in a JUNG graph are connected by more than one path?

StackOverflow https://stackoverflow.com/questions/15835957

  •  01-04-2022
  •  | 
  •  

Question

Given two nodes A and B from a directed JUNG graph, I want to determine whether there is more than one path from A to B (not necessarely a shortest path).

I can think of two approaches only, both very time-consuming.

  1. Retrieve all paths connecting the two nodes (question Finding all paths in JUNG?) and check if there is more than one.

  2. Retrieve the shortest path by using the class DijkstraShortestPath, then break this path and search for the shortest path again. If there is still one, it means there were multiple paths. Note that this also requires to clone the graph, since I do not want to alter the original graph.

How can I do this smarter (i.e. faster)?

Était-ce utile?

La solution

I found a solution myself.

My problem has the additional constraint that I only want to check whether there is more than one path only for two nodes that are directly connected with and edge. This means that by simply computing the shortest path you will always get this single edge as path.

So, my question can be reformulated as:

Is there another path connecting the two nodes of an edge, aside from the edge itself?

The solution is to use a weighted shortest path. If we assign a very high weight to our edge of interest, and weight 1 to all the others, then if the minimal distance is lower than our high weight, the answer is YES, otherwise NO.

Here is the code:

public static boolean areThereMultiplePaths(final Edge edge, DirectedGraph<Entity, Edge> graph) {
        Transformer<Edge, Integer> transformer = new Transformer<Edge, Integer>() {
            public Integer transform(Edge otherEdge) {
                if (otherEdge.equals(edge))
                    return Integer.MAX_VALUE;
                else
                    return 1;
            }
        };

        DijkstraShortestPath<Entity, Edge> algorithm = new DijkstraShortestPath<Entity, Edge>(graph, transformer);
        Double distance = (Double) algorithm.getDistance(edge.getStartNode(), edge.getEndNode());

        return distance < Integer.MAX_VALUE; 
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top