예제 #1
0
  /**
   * Clone a given graph with same node/edge structure and same attributes.
   *
   * @param g the graph to clone
   * @return a copy of g
   */
  public static Graph clone(Graph g) {
    Graph copy;

    try {
      Class<? extends Graph> cls = g.getClass();
      copy = cls.getConstructor(String.class).newInstance(g.getId());
    } catch (Exception e) {
      logger.warning(String.format("Cannot create a graph of %s.", g.getClass().getName()));
      copy = new AdjacencyListGraph(g.getId());
    }

    copyAttributes(g, copy);

    for (int i = 0; i < g.getNodeCount(); i++) {
      Node source = g.getNode(i);
      Node target = copy.addNode(source.getId());

      copyAttributes(source, target);
    }

    for (int i = 0; i < g.getEdgeCount(); i++) {
      Edge source = g.getEdge(i);
      Edge target =
          copy.addEdge(
              source.getId(),
              source.getSourceNode().getId(),
              source.getTargetNode().getId(),
              source.isDirected());

      copyAttributes(source, target);
    }

    return copy;
  }