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

时间:2019-04-06 09:06:45

标签: java shortest-path jgrapht

我使用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之间的边缘方向如何,都有什么方法可以找到路径?

1 个答案:

答案 0 :(得分:2)

您可以使用AsUndirectedGraph类。

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

注意:您可能想使用SimpleDirectedGraph而不是DirectedPseudograph,除非您确实需要多个边/自环。