Search code examples
javashortest-pathjgrapht

JGraphT: Finding shortest path regardless of Edge Direction


I build the following graph A->B<-C using JGraphT as seen below:

    DirectedPseudograph<Node, Edge> graph = new DirectedPseudograph<>(Edge.class);
    DijkstraShortestPath<Node, Edge> shortestPath = new DijkstraShortestPath<Node, Edge>(graph);
    Node bn1 = new Node("1", "A", null);
    Node bn2 = new Node("2", "B", null);
    Node bn3 = new Node("3", "C", null);

    graph.addVertex(bn1);
    graph.addVertex(bn2);
    graph.addVertex(bn3);

    Edge edge1 = new Edge("PART_OF");
    Edge edge2 = new Edge("IS_A");
    graph.addEdge(bn1, bn2, edge1);
    graph.addEdge(bn3, bn2, edge2);

But whenever I try to call:

shortestPath.getPath(node1, node3);

I get an empty array meaning there is no connection. I understand this might have to do with the direction of the edges as A->B->C works fine. Is there any way to find the path regardless of the direction of the edges between A and C?


Solution

  • You can use the AsUndirectedGraph class for that.

    Graph<Node, Edge> graph = new DirectedPseudograph<>(Edge.class);
    Node bn1 = new Node("1", "A", null);
    Node bn2 = new Node("2", "B", null);
    Node bn3 = new Node("3", "C", null);
    
    graph.addVertex(bn1);
    graph.addVertex(bn2);
    graph.addVertex(bn3);
    
    Edge edge1 = new Edge("PART_OF");
    Edge edge2 = new Edge("IS_A");
    graph.addEdge(bn1, bn2, edge1);
    graph.addEdge(bn3, bn2, edge2);
    
    Graph<Node, Edge> undirGraph=new AsUndirectedGraph<>(graph);
    ShortestPathAlgorithm<Node, Edge> shortestPath = new DijkstraShortestPath<Node, Edge>(undirGraph);
    

    Note: you might want to use a SimpleDirectedGraph as opposed to a DirectedPseudograph unless you really need multiple edges/self-loops.