简体   繁体   中英

JGraphT: calculate Graph intersection

Using JGraphT , is it possible to calculate the intersection (difference/delta) of two Graph objects?

Are there any other java graph libraries which can help me solving my problem?

In JUNG, the most straightforward way to solve this is to build the intersection (or whatever other set operation you like) of the vertex and edge sets, and then build another graph out of the results:

(using the Guava Sets class)

Graph<V, E> newGraph = ...; // create the appropriate graph type
for (V v : Sets.intersection(g1.getVertices(), g2.getVertices()) {
  newGraph.addVertex(v);
}

for (E e : Sets.intersection(g1.getEdges(), g2.getEdges()) {
  // Assume that each each e connects the same set of vertices in both
  // g1 and g2.  Otherwise you need to check that as well.
  V v1 = g1.getEndpoints(e).getFirst();
  V v2 = g1.getEndpoints(e).getSecond();
  // This contains check is necessary because the default implementations
  // of addEdge() will add v1 and v2 if they are not already present in
  // the graph, which you don't want to do if they're not in the intersection.
  if (newGraph.containsVertex(v1) && newGraph.containsVertex(v2)) {
    newGraph.addEdge(e, v1, v2);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM