Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package test;
- import org.jgrapht.*;
- import org.jgrapht.alg.interfaces.ShortestPathAlgorithm.SingleSourcePaths;
- import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
- import org.jgrapht.graph.*;
- public class DirectedWeightedGraphTest {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- WeightedGraph<String, DefaultWeightedEdge> g = new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
- // create vertices
- String A = "A";
- String B = "B";
- String C = "C";
- String D = "D";
- String E = "E";
- // add the vertices to g
- g.addVertex(A);
- g.addVertex(B);
- g.addVertex(C);
- g.addVertex(D);
- g.addVertex(E);
- // add edges to g
- g.setEdgeWeight(g.addEdge(A, B), 10);
- g.setEdgeWeight(g.addEdge(A, C), 5);
- g.setEdgeWeight(g.addEdge(B, C), 2);
- g.setEdgeWeight(g.addEdge(B, D), 1);
- g.setEdgeWeight(g.addEdge(C, B), 3);
- g.setEdgeWeight(g.addEdge(C, D), 9);
- g.setEdgeWeight(g.addEdge(C, E), 2);
- g.setEdgeWeight(g.addEdge(D, E), 4);
- g.setEdgeWeight(g.addEdge(E, A), 7);
- g.setEdgeWeight(g.addEdge(E, D), 6);
- DijkstraShortestPath<String, DefaultWeightedEdge> dijAlgorithm = new DijkstraShortestPath<>(g);
- SingleSourcePaths<String, DefaultWeightedEdge> APaths = dijAlgorithm.getPaths("A");
- System.out.println("Shortest Path from A to B:" + APaths.getPath(B));
- System.out.println("Shortest Path from A to C:" + APaths.getPath(C));
- System.out.println("Shortest Path from A to D:" + APaths.getPath(D));
- System.out.println("Shortest Path from A to E:" + APaths.getPath(E));
- }
- }
Add Comment
Please, Sign In to add comment