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.
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.
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.
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.
© 2022 - 2024 — McMap. All rights reserved.