喲已經從here描述Interface WeightedGraph<V,E>
。
您需要使用SimpleDirectedWeightedGraph
來設置其邊緣的權重。 看這個例子中,通過使用graph.addVertex()
,graph.setEdgeWeight()
方法創建Directed Weighted Graph,並通過使用在DijkstraShortestPath.findPathBetween()
方法實現Dijkstra Algorithm考慮一些邊緣之間 最短路徑。
import org.jgrapht.*;
import org.jgrapht.alg.*;
import org.jgrapht.graph.*;
import java.util.List;
public class Graph {
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 shortest_path = DijkstraShortestPath.findPathBetween(graph, "vertex1", "vertex5");
System.out.println(shortest_path);
}
}
它是一個接口。你需要一個實現它的文件來擁有一個字段權重,並且每當它改變一次 –