How to copy a graph in JGraphT?
Asked Answered
H

2

6

I need make a copy of a simple graph.

I don't see a graph duplicator among graph generators and UndirectedGraph doesn't implement a clone method.

Year, I can copy a graph by hands. But I want to do this in one line.

Hiett answered 18/2, 2013 at 14:27 Comment(0)
S
5

UndirectedGraph is an interface. However, most of the concrete subclasses (e.g. SimpleGraph) extend AbstractBaseGraph which does implement the clone() method.

So, if you can guarantee that the UndirectedGraph you have in your hand inherits from AbstractBaseGraph, simply cast to AbstractBaseGraph and call the clone method.

public void someMethod(UndirectedGraph g)
{
  // Do some stuff...

  ((AbstractBaseGraph)g).clone(); // <== Your 1-liner

  // Do some more stuff...
}

Bear in mind though, that according to the JavaDoc, the clone() method does a shallow clone. So the graph instance is cloned but the vertices and edges within it aren't.

Semaphore answered 4/4, 2013 at 19:59 Comment(0)
C
-1

A very crude (but quick) solution to copy a graph would be:

    DirectedGraph<String, DefaultEdge> graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
    DirectedGraph<String, DefaultEdge> revGraph = new EdgeReversedGraph<>(graph);
    DirectedGraph<String, DefaultEdge> graphCopy = new EdgeReversedGraph<>(revGraph);
    //To reduce the memory complexity
    revGraph = null;

However, it is to be kept in mind that the solution would have high memory & computation complexity if the graph is too big. Discarding the intermediate reversed graph would improve the solution.

Cryptoclastic answered 2/1, 2016 at 19:32 Comment(1)
This is just 100% wrong. It does not copy the graph and does not eat significant memory, as it simply delegates all calls to the original graph. SourcePsittacine

© 2022 - 2024 — McMap. All rights reserved.