JGraphT:寻找最短路径而不考虑边缘方向

JGraphT: Finding shortest path regardless of Edge Direction

我使用 JGraphT 构建了以下图表 A->B<-C,如下所示:

    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);

但是每当我尝试调用:

shortestPath.getPath(node1, node3);

我得到一个空数组,表示没有连接。我知道这可能与边缘的方向有关,因为 A->B->C 工作正常。有没有办法不管A和C之间边的方向如何都能找到路径?

您可以使用 AsUndirectedGraph class。

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);

注意:除非您确实需要多个 edges/self-loops.

,否则您可能希望使用 SimpleDirectedGraph 而不是 DirectedPseudograph