为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

江户川乱折腾 2022-09-22 16:00:30

我使用 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 回答

?
鸿蒙传说

TA贡献1533条经验 获得超7个赞

您可以使用无向图类来实现此目的。

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

注意:您可能希望使用 与 a 相对,除非您确实需要多个边/自循环。SimpleDirectedGraphDirectedPseudograph


查看完整回答
反对 回复 2022-09-22

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信