문제

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 ;
    }
도움이 되었습니까?

해결책

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top