Question

I am looking for an efficient way of finding the set of all nodes that are reachable from specific collection of nodes in JUNG. I am not sure how to do that. One solution would be to get the neighbors of each node of specific collection and do that until no new node added regarding to this process. But I think probably a more efficient way would be available. Could you please tell me what would it be? (below is the code of my implementation)

private HashSet<Customer> getReachableNodes(Collection<Customer> churners, DirectedSparseGraph<Customer, Transaction> net) {

        HashSet<Customer> reachableNode = new HashSet<Customer>();
        for (Customer churner : churners) {
            for(Customer neighbor:net.getVertices()){
                 if(isNeighbor(neighbor,churners,net))   reachableNode.add(neighbor)
            }
        }
        return reachableNode ;
    }
Was it helpful?

Solution

A straightforward approach could be to do a simple Breadth-first traversal ( http://en.wikipedia.org/wiki/Breadth-first_search ), but with a collection of "start nodes" instead of a single one:

private static <V> Set<V> findReachable(
    Collection<? extends V> startNodes, Graph<V, ?> graph)
{
    Queue<V> queue = new LinkedList<V>();
    Set<V> visited = new LinkedHashSet<V>();
    queue.addAll(startNodes);
    visited.addAll(startNodes);
    while(!queue.isEmpty()) 
    {
        V v = queue.poll();
        Collection<V> neighbors = graph.getNeighbors(v);
        for (V n : neighbors)
        {
            if (!visited.contains(n))
            {
                queue.offer(n);
                visited.add(n);
            }
        }
    }
    return visited;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top