Shortest Path Algorithm

Download

Download jar file or use maven. psjava requires Java 1.6 (or above)

<dependency>
    <groupId>org.psjava</groupId>
    <artifactId>psjava</artifactId>
    <version>0.1.19</version>
</dependency>

Example Code

// Let's construct a graph.

MutableDirectedWeightedGraph<String, Integer> graph = MutableDirectedWeightedGraph.create();
graph.insertVertex("A");
graph.insertVertex("B");
graph.insertVertex("C");
graph.insertVertex("D");
graph.addEdge("A", "C", 100);
graph.addEdge("A", "B", 10);
graph.addEdge("B", "C", 20);

// Then calculate distances from a single source 'A'
// Choose algorithm, and run it.

SingleSourceShortestPathAlgorithm algorithm1 = GoodSingleSourceShortestPathAlgorithm.getInstance();
SingleSourceShortestPathResult<String, Integer, DirectedWeightedEdge<String, Integer>> res1 = algorithm1.calc(graph, "A", IntegerNumberSystem.getInstance());

int distanceAToC = res1.getDistance("C");
boolean reachabilityOfD = res1.isReachable("D");

// Let's get the shortest paths of all pairs. Floyd Warshall's algorithm is the simplest implementation.

AllPairShortestPath algoritm2 = FloydWarshallAlgorithm.getInstance();
AllPairShortestPathResult<String, Integer, DirectedWeightedEdge<String, Integer>> res2 = algoritm2.calc(graph, IntegerNumberSystem.getInstance());

int distanceAToB = res2.getDistance("A", "B");
int distanceBToC = res2.getDistance("B", "C");

See Also


Copyright 2014 psjava team. View on GitHub