Johnson 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.addEdge("A", "C", 10);
graph.addEdge("A", "B", 15);
graph.addEdge("B", "C", -10); // negative weight is allowed in Johnson's algorithm
graph.addEdge("C", "A", 5);

// Let's get the shortest paths of all pairs.
// Johnson's algorithm is a combination of Bellman Ford's and Dijkstra's algorithm.

AllPairShortestPath johnson = GoodJohnsonAlgorithm.getInstance();
AllPairShortestPathResult<String, Integer, DirectedWeightedEdge<String, Integer>> res = johnson.calc(graph, IntegerNumberSystem.getInstance());

int distanceAToB = res.getDistance("A", "B"); // must be 15
int distanceBToC = res.getDistance("B", "A"); // must be -5

See Also

Implementation


Copyright 2014 psjava team. View on GitHub