gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:41:52 28 4
gpt4 key购买 nike

我使用 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类。

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 除非您确实需要多边/自循环。

关于java - JGraphT:寻找最短路径而不考虑边缘方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55547521/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com