Search code examples
javajgraphtjgraph

How to represent bi-directional edges in graph


So I'm using the JGraphT library and I have a method already to create a two-directional edges in my program.

However when I display the graph, it currently displays the return direction like so:

D1 -> D2
D2 -> D1

When I would prefer it to be as follows:

D1 <-> D2

Here is the code that I am using so far:

for(String vertex : destinations) {
    Set<DefaultWeightedEdge> edges = graph.outgoingEdgesOf(vertex);
    for(DefaultWeightedEdge edge : edges) {
        System.out.println(graph.getEdgeSource(edge) + " -> " + graph.getEdgeTarget(edge));
    }
}

For reference this is the destinations list that i use:

ArrayList<String> destinations = new ArrayList<String>();
destinations.add("Amsterdam");
destinations.add("Boston");
destinations.add("Chicago");
destinations.add("Edinburgh");
destinations.add("Heathrow");
destinations.add("Hong Kong");
destinations.add("Montreal");
destinations.add("New Delhi");
destinations.add("Shanghai");
destinations.add("Toronto");

Solution

  • May be not the nicest code:

    for (String source: destinations) {
        Set<DefaultWeightedEdge> edges = graph.outgoingEdgesOf(source);
        for (DefaultWeightedEdge edge : edges) {
            //String source = graph.getEdgeSource(edge);
            String target = graph.getEdgeTarget(edge);
            boolean comingBack = graph.containsEdge(target, source);
            if (comingBack && source.compareTo(target) > 0) {
                continue; // Skip B <-> A as already A <-> B.
            }
            String arrow = comingBack ? "<->" : "->";
            System.out.printf("%s %s %s%n", source, arrow, target);
        }
    }