以下是使用BreathFirstIterator
遍历图表的代码:
public class GraphTest {
public static void main(String[] args) {
DirectedGraph<Integer, DefaultEdge> graph =
new DefaultDirectedGraph <Integer, DefaultEdge>(DefaultEdge.class);
graph.addVertex(7);
graph.addVertex(4);
graph.addVertex(9);
graph.addVertex(3);
graph.addVertex(2);
graph.addVertex(5);
graph.addEdge(7, 4);
graph.addEdge(7, 9);
graph.addEdge(9, 3);
graph.addEdge(3, 2);
graph.addEdge(3, 5);
GraphIterator<Integer, DefaultEdge> iterator =
new BreadthFirstIterator<Integer, DefaultEdge>(graph);
while (iterator.hasNext()) {
System.out.println( iterator.next() );
}
}
}
正如预期的那样,代码打印出所有访问过的顶点的列表:7,4,9,3,2,5
。我的问题是 - 我不知道如何使用此API来获取已删除算法回溯的路径。例如,对于从7到2的路径,它将输出7->9->3->2
,而不仅仅是访问的顶点列表。到达目的地后停止它是不够的。有人已经解决了这个问题吗?
答案 0 :(得分:1)
可以使用DijkstraShortestPath.findPathBetween
获得两个顶点之间的最短路径。它使用ClosestFirstIterator
提供Dijkstra's shortest path algorithm的实施。如果没有这样的路径,它将返回null
。
示例代码:
DirectedGraph<Integer, DefaultEdge> graph = new DefaultDirectedGraph<>(DefaultEdge.class);
graph.addVertex(7);
graph.addVertex(4);
graph.addVertex(9);
graph.addVertex(3);
graph.addVertex(2);
graph.addVertex(5);
graph.addEdge(7, 4);
graph.addEdge(7, 9);
graph.addEdge(9, 3);
graph.addEdge(3, 2);
graph.addEdge(3, 5);
List<DefaultEdge> path = DijkstraShortestPath.findPathBetween(graph, 7, 2);
System.out.println(path); // prints [(7 : 9), (9 : 3), (3 : 2)]