Search code examples
javajgraphtsubgraph

how to create a subgraph with jgrapht


I am using jgrapht in Java to work a network-based algorithm. I first read an adjacency list and then create jgrapht based graph. Now, given a subset of nodes called subNodes, I'd like to generate a sub graph. I am trying to use Subgraph class as shown at this link, however, I could not have it worked.

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

A similar post is here, but that also did not help.


Solution

  • It seems you are referring to some old javadoc. Not sure why you are specifically using the 1.1.0. Here's an example using the 1.5 version of 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);
        }
    }
    

    Output:

    Graph: ([1, 2, 3, 4], [{1,2}, {2,3}, {3,4}, {4,1}])
    Subgraph: ([1, 2], [{1,2}])
    

    You should always have a look at the examples included in the test directories. The AsSubgraph class comes with the AsSubgraphTest class which can be found in the test suite. The latest javadoc (1.5.0 at the time of writing) can be found here: https://jgrapht.org/javadoc/