Search code examples
javagraphjgrapht

JGraphT: get neighbor nodes


I have a simple undirected graph G = (V, E). Given a node n, is there an easy way to find all its neighbors, i.e. all nodes m, such that {n, m} in E?

There's edgesOf method, which returns all edges connected to given node. However, it seems that in an undirected graph it's somewhat arbitrary, which node is the source and which is the target.

I guess I could simply check whether my node is the source or the target and then the other node is the neighbor I'm looking for, but that's clunky. Is there a more elegant way?


Solution

  • You can do it through neighborListOf(Graph g, V vertex), e.g.:

        Graph<String, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class);
    
        String v1 = "v1";
        String v2 = "v2";
        String v3 = "v3";
        String v4 = "v4";
    
        g.addVertex(v1);
        g.addVertex(v2);
        g.addVertex(v3);
        g.addVertex(v4);
    
        g.addEdge(v1, v2);
        g.addEdge(v2, v3);
        g.addEdge(v3, v4);
        g.addEdge(v4, v1);
    
        System.out.println(Graphs.neighborListOf(g, v1));