Skip to content

Instantly share code, notes, and snippets.

@mvaz mvaz/gist:973464
Created May 15, 2011

What would you like to do?
Graph listener example
package net.mvaz.examples.graph;
import org.jgrapht.DirectedGraph;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.event.ConnectedComponentTraversalEvent;
import org.jgrapht.event.TraversalListenerAdapter;
import org.jgrapht.event.VertexTraversalEvent;
import org.jgrapht.graph.SimpleDirectedGraph;
import org.jgrapht.traverse.DepthFirstIterator;
import org.jgrapht.traverse.GraphIterator;
public class JGraphtTraversalExample {
static class MyListener extends TraversalListenerAdapter<String, String> {
DirectedGraph<String, String> g;
private boolean newComponent;
private String reference;
public MyListener(DirectedGraph<String, String> g) {
this.g = g;
public void connectedComponentStarted(ConnectedComponentTraversalEvent e) {
newComponent = true;
public void vertexTraversed(VertexTraversalEvent<String> e) {
String vertex = e.getVertex();
if (newComponent) {
reference = vertex;
newComponent = false;
int l = DijkstraShortestPath.findPathBetween( g, reference, vertex).size();
String x = "";
for (int i=0; i<l; i++) x+= "\t";
System.out.println( x + "vertex: " + vertex);
* @param args
public static void main(String[] args) {
DirectedGraph<String,String> g = new SimpleDirectedGraph<String, String>(String.class);
g.addEdge("A", "B", "e1");
g.addEdge("A", "C", "e2");
g.addEdge("C", "D", "e3");
GraphIterator<String, String> iterator = new DepthFirstIterator<String, String>(g);
iterator.addTraversalListener( new MyListener( g));
while (iterator.hasNext()) {;
// System.out.println( );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.