How to reverse Jung DirectedGraph?

129 views Asked by At

I am using JUNG DirectedGraph and I need to transform a given directed graph to a reversed graph, so that the newly created graph contains all vertices and edges from the original graph and all edges in the new graph are reversed. I need to perform this transformation on the model.
Is there a JUNG utility that provides this functionality? I use JUNG version 2.0.1. I realize it's easy to implement, just prefer to use the provided utility if available.

Thanks

2

There are 2 answers

0
Uli Köhler On BEST ANSWER

After searching a large portion of the JUNG2 API, I assume there is no such utility. What would be needed is an edge transformation function, but even if there are many applications for it, there seem to be no traces of any such utility function.

Depending on your application, a different approach might be worth a look: You could subclass DirectedGraph, implementing a wrapper for any existing Graph that inverts edges on the fly. Specifically, getInEdges() would return getOutEdges() and vice versa. You still need to wrap other functions that depend on the Edge direction.

Depending on your application, this approach might or might not be simpler than simply copying the edges.

0
Joshua O'Madadhain On

JUNG does not provide such a utility. The code to do it would be pretty simple, though:

for (E edge : graph.getEdges()) {
  graph2.addEdge(edge, graph.getDestination(edge), graph.getSource(edge));
}

(If the graph can have any isolated vertices, then you would need a second loop to copy graph's vertices to graph2.)

Uli's suggestion (to wrap the graph and turn around the edge direction on the fly, e.g. using GraphDecorator) would also work fine. Which one you would prefer depends on (a) how much code you want to write and (b) whether you want a view or a copy of graph (with reversed edge direction).

Another option: if you are writing code that is specifically intended for use with such a direction-reversed graph, then you could simply swap calls to getInEdges() to getOutEdges(), etc. That might be the simplest option.