How to unite two graphs in JUNG?

只谈情不闲聊 提交于 2019-12-24 21:20:24

问题


I have to graphs which I want to unite, that is, create a new graph composed by the union of both graph's edges and nodes (without repetition). Is there an implementation for that avaliable in JUNG or do I have do so on my own?


回答1:


There isn't an implementation for that in JUNG, but it's about six lines of code assuming that the graphs, vertices, and edges are of the same types:

// given Graph g1, g2
Graph g = new [appropriate Graph implementation]
for (V v : Collections.union(g1.getVertices(), g2.getVertices())) {
  g.addVertex(v);
}
for (E e : g1.getEdges()) {
  g.addEdge(e, g1.getEndpoints(e));
}
for (E e : g2.getEdges()) {
  g.addEdge(e, g2.getEndpoints(e));
}

You can skip the vertex adding if there are no isolated vertices (i.e., vertices that have no incident edges); addEdge() will add any incident vertices.

If the graph is directed, you'll want to change the above to

g.addEdge(e, g1.getSource(e), g1.getDest(e));

Duplicates are silently ignored (if you want to know whether an add had an effect, check the return value).



来源:https://stackoverflow.com/questions/7165345/how-to-unite-two-graphs-in-jung

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!