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>
// Let's prepare a simple graph.
MutableDirectedUnweightedGraph<String> g = MutableDirectedUnweightedGraph.create();
g.insertVertex("A");
g.insertVertex("B");
g.insertVertex("C");
g.insertVertex("D");
g.addEdge("A", "B");
g.addEdge("B", "C");
g.addEdge("C", "D");
g.addEdge("B", "D");
// Then find a path from "A" to "D" by BFS.
Collection<String> starts = SingleElementCollection.create("A"); // You can specify multiple vertices. But here is one start vertex.
BFS.traverse(g, starts, new BFSVisitor<String, DirectedEdge<String>>() {
@Override
public void onDiscover(String vertex, int depth, VisitorStopper stopper) {
if (vertex.equals("D")) {
// There is a path: A->B->D, so depth is 2.
int pathLength = depth;
// when you call the stopper, BFS stops. So no other vertex will be discovered.
stopper.stop();
}
}
@Override
public void onWalk(DirectedEdge<String> e) {
// You can also track the sequence of discovering edges.
}
});
Copyright 2014 psjava team. View on GitHub