2 * Copyright (c) 2003, the JUNG Project and the Regents of the University
6 * This software is open-source under the BSD license; see either
8 * http://jung.sourceforge.net/license.txt for a description.
10 package edu.uci.ics.jung.algorithms.cluster;
12 import java.util.Collection;
13 import java.util.HashSet;
16 import org.apache.commons.collections15.Buffer;
17 import org.apache.commons.collections15.Transformer;
18 import org.apache.commons.collections15.buffer.UnboundedFifoBuffer;
20 import edu.uci.ics.jung.graph.Graph;
25 * Finds all weak components in a graph as sets of vertex sets. A weak component is defined as
26 * a maximal subgraph in which all pairs of vertices in the subgraph are reachable from one
27 * another in the underlying undirected subgraph.
28 * <p>This implementation identifies components as sets of vertex sets.
29 * To create the induced graphs from any or all of these vertex sets,
30 * see <code>algorithms.filters.FilterUtils</code>.
32 * Running time: O(|V| + |E|) where |V| is the number of vertices and |E| is the number of edges.
35 public class WeakComponentClusterer<V,E> implements Transformer<Graph<V,E>, Set<Set<V>>>
38 * Extracts the weak components from a graph.
39 * @param graph the graph whose weak components are to be extracted
40 * @return the list of weak components
42 public Set<Set<V>> transform(Graph<V,E> graph) {
44 Set<Set<V>> clusterSet = new HashSet<Set<V>>();
46 HashSet<V> unvisitedVertices = new HashSet<V>(graph.getVertices());
48 while (!unvisitedVertices.isEmpty()) {
49 Set<V> cluster = new HashSet<V>();
50 V root = unvisitedVertices.iterator().next();
51 unvisitedVertices.remove(root);
54 Buffer<V> queue = new UnboundedFifoBuffer<V>();
57 while (!queue.isEmpty()) {
58 V currentVertex = queue.remove();
59 Collection<V> neighbors = graph.getNeighbors(currentVertex);
61 for(V neighbor : neighbors) {
62 if (unvisitedVertices.contains(neighbor)) {
64 unvisitedVertices.remove(neighbor);
65 cluster.add(neighbor);
69 clusterSet.add(cluster);