以下是使用Dijkstra算法查找最短路径的示例代码:

public static void main(String args[]) {
    SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> graph = new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
    graph.addVertex("vertex1");
    graph.addVertex("vertex2");
    graph.addVertex("vertex3");
    graph.addVertex("vertex4");
    graph.addVertex("vertex5");

    DefaultWeightedEdge e1 = graph.addEdge("vertex1", "vertex2");
    graph.setEdgeWeight(e1, 5);

    DefaultWeightedEdge e2 = graph.addEdge("vertex2", "vertex3");
    graph.setEdgeWeight(e2, 3);

    DefaultWeightedEdge e3 = graph.addEdge("vertex4", "vertex5");
    graph.setEdgeWeight(e3, 6);

    DefaultWeightedEdge e4 = graph.addEdge("vertex2", "vertex4");
    graph.setEdgeWeight(e4, 2);

    DefaultWeightedEdge e5 = graph.addEdge("vertex5", "vertex4");
    graph.setEdgeWeight(e5, 4);

    DefaultWeightedEdge e6 = graph.addEdge("vertex2", "vertex5");
    graph.setEdgeWeight(e6, 9);

    DefaultWeightedEdge e7 = graph.addEdge("vertex4", "vertex1");
    graph.setEdgeWeight(e7, 7);

    DefaultWeightedEdge e8 = graph.addEdge("vertex3", "vertex2");
    graph.setEdgeWeight(e8, 2);

    DefaultWeightedEdge e9 = graph.addEdge("vertex1", "vertex3");
    graph.setEdgeWeight(e9, 10);

    DefaultWeightedEdge e10 = graph.addEdge("vertex3", "vertex5");
    graph.setEdgeWeight(e10, 1);

    System.out.println("Shortest path from vertex1 to vertex5:");
    List<DefaultWeightedEdge> shortest_path = DijkstraShortestPath.findPathBetween(graph,"vertex1", "vertex5");
    System.out.println(shortest_path);
}


是否有可能获得已到达并被算法标记为已访问节点的列表?我已经看到有一个叫做TraversalListener的东西,但它似乎仅适用于迭代器,例如Br​​eadthFirstIterator。

最佳答案

使用DijkstraShortestPath类似乎对此没有任何便利。这是因为遍历侦听器已添加到图形迭代器,并且无法访问DijkstraShortestPath使用的迭代器。

因此,唯一的解决方案是将DijkstraShortestPath代码复制到一个新类中(我们称之为MyDijkstraShortestPath)并添加遍历侦听器。

首先,您需要创建一个从MyTraversalListener继承的类TraversalListenerAdapter,并覆盖所需的方法。

class MyTraversalListener<V, E> extends TraversalListenerAdapter<V, E> {
     // override the method you want, like vertexTraversed and edgeTraversed
}


然后,在新的MyDijkstraShortestPath类的构造函数中,我们需要添加它:

ClosestFirstIterator<V, E> iter =
    new ClosestFirstIterator<V, E>(graph, startVertex, radius);
iter.addTraversalListener(new MyTraversalListener<V, E>());

10-08 08:16