Mhazard

JGraphT Simple Directed Weighted Graph

Feb 9th, 2018
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package test;
  2.  
  3. import org.jgrapht.*;
  4. import org.jgrapht.alg.interfaces.ShortestPathAlgorithm.SingleSourcePaths;
  5. import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
  6. import org.jgrapht.graph.*;
  7.  
  8. public class DirectedWeightedGraphTest {
  9.  
  10.     public static void main(String[] args) {
  11.         // TODO Auto-generated method stub
  12.  
  13.         WeightedGraph<String, DefaultWeightedEdge> g = new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
  14.  
  15.         // create vertices
  16.         String A = "A";
  17.         String B = "B";
  18.         String C = "C";
  19.         String D = "D";
  20.         String E = "E";    
  21.  
  22.  
  23.         // add the vertices to g
  24.         g.addVertex(A);
  25.         g.addVertex(B);
  26.         g.addVertex(C);
  27.         g.addVertex(D);
  28.         g.addVertex(E);
  29.        
  30.         // add edges to g
  31.         g.setEdgeWeight(g.addEdge(A, B), 10);
  32.         g.setEdgeWeight(g.addEdge(A, C), 5);
  33.         g.setEdgeWeight(g.addEdge(B, C), 2);
  34.         g.setEdgeWeight(g.addEdge(B, D), 1);
  35.         g.setEdgeWeight(g.addEdge(C, B), 3);
  36.         g.setEdgeWeight(g.addEdge(C, D), 9);
  37.         g.setEdgeWeight(g.addEdge(C, E), 2);
  38.         g.setEdgeWeight(g.addEdge(D, E), 4);
  39.         g.setEdgeWeight(g.addEdge(E, A), 7);
  40.         g.setEdgeWeight(g.addEdge(E, D), 6);
  41.  
  42.         DijkstraShortestPath<String, DefaultWeightedEdge> dijAlgorithm = new DijkstraShortestPath<>(g);
  43.         SingleSourcePaths<String, DefaultWeightedEdge> APaths = dijAlgorithm.getPaths("A");
  44.                
  45.         System.out.println("Shortest Path from A to B:" + APaths.getPath(B));
  46.         System.out.println("Shortest Path from A to C:" + APaths.getPath(C));
  47.         System.out.println("Shortest Path from A to D:" + APaths.getPath(D));
  48.         System.out.println("Shortest Path from A to E:" + APaths.getPath(E));
  49.     }
  50.  
  51. }
Add Comment
Please, Sign In to add comment