我正在使用Java中的jgrapht来处理基于网络的算法。我首先读取邻接表,然后创建基于jgrapht的图。现在,给定一个名为subNodes的节点子集,我想生成一个子图。我正在尝试使用this link中显示的Subgraph类,但是,我不能让它工作。
import org.jgrapht.*;
import org.jgrapht.graph.*;
......
HashMap<Integer, HashSet<Integer>> adjacencyList = new HashMap<Integer, HashSet<Integer>>();
\\fill out adjacency list
\\create your graph
Graph<Integer, DefaultEdge> myGraph = new SimpleGraph<>(DefaultEdge.class);
int numNodes = ...;
for(int i = 0 ; i <numNodes; i++)
myGraph.addVertex(i);
for(int i = 0 ; i< numNodes; i++) {
if(adjacencyList.get(i) != null) {
for(Integer j : adjacencyList.get(i)) {
myGraph.addEdge(i, j);
}
}
}
Set<Integer> subNodes = new HashSet<Integer>();
\\generate a sub set of vertices to have a subgprah类似的帖子是here,但这也没有帮助。
发布于 2020-09-25 01:01:51
看起来你指的是一些老的javadoc。不确定为什么要特别使用1.1.0。下面是一个使用1.5版本的jgrapht的例子:
public class SubGraphExample {
public static void main(String[] args){
Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class);
Graphs.addAllVertices(g, Arrays.asList(1,2,3,4));
g.addEdge(1,2);
g.addEdge(2,3);
g.addEdge(3,4);
g.addEdge(4,1);
System.out.println("Graph: "+g);
//Subgraph
Set<Integer> vertexSubset = new HashSet<>(Arrays.asList(1,2));
Graph<Integer, DefaultEdge> subgraph = new AsSubgraph<>(g, vertexSubset);
System.out.println("Subgraph: "+subgraph);
}
}输出:
Graph: ([1, 2, 3, 4], [{1,2}, {2,3}, {3,4}, {4,1}])
Subgraph: ([1, 2], [{1,2}])您应该始终查看测试目录中包含的示例。AsSubgraph类附带了AsSubgraphTest类,可以在test suite中找到该类。最新的javadoc (在撰写本文时为1.5.0)可以在这里找到:https://jgrapht.org/javadoc/
https://stackoverflow.com/questions/64032963
复制相似问题