構建如下圖會告訴你,你要尋找的路徑:
DefaultDirectedWeightedGraph<String, DefaultWeightedEdge> g;
g = new DefaultDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
g.addVertex("a");
g.addVertex("b");
g.addVertex("c");
g.addVertex("d");
DefaultWeightedEdge edge1 = g.addEdge("a", "b");
g.setEdgeWeight(edge1, 10);
DefaultWeightedEdge edge1a = g.addEdge("b", "a");
g.setEdgeWeight(edge1a, 10);
DefaultWeightedEdge edge2 = g.addEdge("a", "c");
g.setEdgeWeight(edge2, 10);
DefaultWeightedEdge edge2a = g.addEdge("c", "a");
g.setEdgeWeight(edge2a, 10);
DefaultWeightedEdge edge3 = g.addEdge("b", "c");
g.setEdgeWeight(edge3, -1);
DefaultWeightedEdge edge3a = g.addEdge("c", "b");
g.setEdgeWeight(edge3a, -1);
DefaultWeightedEdge edge4 = g.addEdge("b", "d");
g.setEdgeWeight(edge4, 10);
DefaultWeightedEdge edge4a = g.addEdge("d", "b");
g.setEdgeWeight(edge4a, 10);
List<DefaultWeightedEdge> path = BellmanFordShortestPath.findPathBetween(g, "a", "d");
System.out.println(path);
上面會輸出:
[(a : c), (c : b), (b : d)]