edu.stanford.nlp.graph.ConnectedComponents Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of stanford-parser Show documentation
Show all versions of stanford-parser Show documentation
Stanford Parser processes raw text in English, Chinese, German, Arabic, and French, and extracts constituency parse trees.
package edu.stanford.nlp.graph;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import edu.stanford.nlp.util.CollectionUtils;
import edu.stanford.nlp.util.Generics;
/**
* Finds connected components in the graph, currently uses inefficient list for
* variable 'verticesLeft'. It might give a problem for big graphs
*
* @author sonalg 08/08/11
*/
public class ConnectedComponents {
public static List> getConnectedComponents(Graph graph) {
List> ccs = new ArrayList>();
LinkedList todo = new LinkedList();
// TODO: why not a set?
List verticesLeft = CollectionUtils.toList(graph.getAllVertices());
while (verticesLeft.size() > 0) {
todo.add(verticesLeft.get(0));
verticesLeft.remove(0);
ccs.add(bfs(todo, graph, verticesLeft));
}
return ccs;
}
private static Set bfs(LinkedList todo, Graph graph, List verticesLeft) {
Set cc = Generics.newHashSet();
while (todo.size() > 0) {
V node = todo.removeFirst();
cc.add(node);
for (V neighbor : graph.getNeighbors(node)) {
if (verticesLeft.contains(neighbor)) {
cc.add(neighbor);
todo.add(neighbor);
verticesLeft.remove(neighbor);
}
}
}
return cc;
}
}